The bubble sort is slow and I thought it would be interesting to visualize the progress as it sorts an array of integers.
Progress of a Bubble Sort (C)
// show the progress of a bubblesort of an array of integers
#include <stdio.h>
#define NUM_ITEMS 10
void bubbleSort(int numbers[], int array_size);
void show(int numbers[], int array_size);
int main(void)
{
int k;
int numbers[NUM_ITEMS] = {8, 10, 6, 7, 4, 5, 9, 1, 3, 2};
//perform bubble sort on array
bubbleSort(numbers, NUM_ITEMS);
puts("--------------------------------------");
show(numbers, NUM_ITEMS);
getchar(); // wait
return 0;
}
void bubbleSort(int numbers[], int array_size)
{
int finished = 0, i, j, temp;
for (i = (array_size - 1); i >= 0; i--)
{
if (finished)
break;
finished = 1;
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
finished = 0;
// swap
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
show(numbers, NUM_ITEMS);
}
}
}
void show(int numbers[], int array_size)
{
int k;
for (k = 0; k < array_size; k++)
printf("%2d ", numbers[k]);
puts("");
}
/* output ...
8 10 6 7 4 5 9 1 3 2
8 6 10 7 4 5 9 1 3 2
8 6 7 10 4 5 9 1 3 2
8 6 7 4 10 5 9 1 3 2
8 6 7 4 5 10 9 1 3 2
8 6 7 4 5 9 10 1 3 2
8 6 7 4 5 9 1 10 3 2
8 6 7 4 5 9 1 3 10 2
8 6 7 4 5 9 1 3 2 10
6 8 7 4 5 9 1 3 2 10
6 7 8 4 5 9 1 3 2 10
6 7 4 8 5 9 1 3 2 10
6 7 4 5 8 9 1 3 2 10
6 7 4 5 8 9 1 3 2 10
6 7 4 5 8 1 9 3 2 10
6 7 4 5 8 1 3 9 2 10
6 7 4 5 8 1 3 2 9 10
6 7 4 5 8 1 3 2 9 10
6 4 7 5 8 1 3 2 9 10
6 4 5 7 8 1 3 2 9 10
6 4 5 7 8 1 3 2 9 10
6 4 5 7 1 8 3 2 9 10
6 4 5 7 1 3 8 2 9 10
6 4 5 7 1 3 2 8 9 10
4 6 5 7 1 3 2 8 9 10
4 5 6 7 1 3 2 8 9 10
4 5 6 7 1 3 2 8 9 10
4 5 6 1 7 3 2 8 9 10
4 5 6 1 3 7 2 8 9 10
4 5 6 1 3 2 7 8 9 10
4 5 6 1 3 2 7 8 9 10
4 5 6 1 3 2 7 8 9 10
4 5 1 6 3 2 7 8 9 10
4 5 1 3 6 2 7 8 9 10
4 5 1 3 2 6 7 8 9 10
4 5 1 3 2 6 7 8 9 10
4 1 5 3 2 6 7 8 9 10
4 1 3 5 2 6 7 8 9 10
4 1 3 2 5 6 7 8 9 10
1 4 3 2 5 6 7 8 9 10
1 3 4 2 5 6 7 8 9 10
1 3 2 4 5 6 7 8 9 10
1 3 2 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
--------------------------------------
1 2 3 4 5 6 7 8 9 10
*/
hust921 3 Newbie Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
ankur.pandey.52687 0 Newbie Poster
hust921 3 Newbie Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
hust921 3 Newbie Poster
xiangwang 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
David_50 13 Junior Poster in Training
David W 131 Practically a Posting Shark
David_50 13 Junior Poster in Training
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.