Bubble Sort
In bubble sort, each element is compared with its adjacent element, if the first element is larger than the second one then the position of the elements are interchanged otherwise it is not changed. Then next element is compared with its adjacent element and the same process is repeated for all elements in the array.
During the next pass the same process is repeated leaving the largest element. During the pass, the second largest element occupies the second last position.
During the next pass, the same process is repeated leaving the largest element. During this pass, the largest element occupies the n-1 position. This process is repeated until no more elements are left for comparisons. Finally array is sorted one.
Algorithm :
The following is a C program source code for a 5-integer sorting of Bubble. The code sorts the elements in ascending order.
#include
void swap_node(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
void bubble_sort(int elements[], int count)
{
int step, index;
printf("Bubble sort started-\n");
for (step = 0; step < count - 1; step++)
{
printf("==== Step %d ====\n", step + 1);
print_array(elements, 5);
for (index = 0; index < (count - step - 1); index++)
{
printf("#%d ", index + 1);
if (elements[index] > elements[index + 1])
{
printf(" swap %d > %d\n",
elements[index],
elements[index + 1]);
swap_node(&elements[index],
&elements[index + 1]);
}
else
{
printf("no swap %d <= %d\n",
elements[index],
elements[index + 1]);
}
print_array(elements, 5);
}
}
printf("Bubble sort ended\n");
}
void print_array(int array[], int count)
{
int i;
printf("[");
for (i = 0; i < count; i++)
printf("%d, ", array[i]);
printf("\b\b]\n");
}
int main(int argc, char *argv[])
{
int array[5] = { 4, 9, 5, 1, 0 };
printf("Unsorted elements\n");
print_array(array, 5);
bubble_sort(array, 5);
printf("Bubble sorted elements\n");
print_array(array, 5);
}
Output:
Output: