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