Bubble Sort – Sorting in C++ – 1
February 15, 2011 Leave a comment
Given an array of elements, the bubble sort algorithm for sorting the elements in no-descending order proceeds as follows:
Compare the first element with the 2nd. If the 1st element is greater, swap. Now, compare the 2nd and the 3rd elements. If the 2nd is greater than the 3rd, swap. Continue doing this until you reach the end of the array, at which point the largest element has been placed at the last position. Now do the same to place the 2nd largest element at its rightful position, then the 3rd largest at its rightful position, and so on.
void bubble_sort (int A [ ], int n)
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-1-i; j++)
if (A[j] > A[j+1])
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
Running time: Average case/ Worst case / Best case : O(n^2).