Bubble Sort – Sorting in C++ – 1

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)


int temp;

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).


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: