Bubble Sort : Sample program for bubble sort

27/10/2009 ·

Bubble sort works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.



void BubbleSort(int a[], int n)
{
int i, j;// needed for the loops
int tmp;// needed for swapping values between two variables

if (n <= 1) return;// check if the array has no elements or has 1 element
// in that case there is no need of sorting
i = 1;// initializing the variable i
do// the start of a do/while loop
{


for (j = n - 1; j >= i; --j)// for loop that goes backwards and compares
{

if (a[j-1] > a[j])// if the condition is met then swap
{
tmp = a[j-1];
a[j-1] = a[j];
a[j] = tmp;
}
}

} while (++i < n);
}

0 comments:

Post a Comment

Submit Request

If you need some code or programs just post a comment on this post. I will try to provide you the same at the earliest.

About this blog

Free sample code, example code , code snippet , tutorials in C C++. Find, download and reuse the code database available which vary from small programs to large ones as well. Feel free to request for code that is not in the list.

Followers