Bubble Sort Algorithm The idea of Bubble or exchange sort is to scan through

Bubble sort algorithm the idea of bubble or exchange

This preview shows page 12 - 13 out of 13 pages.

Bubble Sort Algorithm The idea of Bubble (or exchange) sort is to scan through the list and swap each pair of adjacent elements that are in the wrong order. The process is repeated each time from index zero to one less than the previous limit until either the list is exhausted or until a pass that involve no swap is encountered. At the end of first pass, the largest element will move (or bubble up) to the end of the list. At the end of the second swap, the second largest will move to its right place, etc. The following table shows a trace of how bubble sort works.
13 Bubble Sort Implementation #include <stdio.h> #define SIZE 10 void bubble_sort(double a[], int size); void read_array(double a[], int size); void print_array(double a[], int size); void swap(double *a, double *b); int main(void) { double x[SIZE]; int i; read_array(x, SIZE); printf("Before Sorting: "); print_array(x, SIZE); bubble_sort(x, SIZE); printf("After Sorting: "); print_array(x, SIZE); system("pause"); return 0; } void swap(double *a, double *b) { double temp = *a; *a = *b; *b = temp; } void bubble_sort(double a[], int size) { int i, pass = 1, swap_occurs; do{ swap_occurs = 0; for(i = 1; i <= size - pass; i++) { if (a[i - 1] > a[i]) { swap(&a[i-1], &a[i]); swap_occurs = 1; } } pass++; } while (swap_occurs && pass <= size-1); } void read_array (double a[], int size) { int i; printf("Enter %d integer numbers separated by blanks\n> ", size); for (i = 0; i < size; ++i) scanf("%lf", &a[i]); } void print_array(double a[], int size) { int i; for (i = 0; i < size; ++i) printf("%.1f ", a[i]); printf("\n"); }

You've reached the end of your free preview.

Want to read all 13 pages?

• Spring '10
• baleh
• int size
Stuck? We have tutors online 24/7 who can help you get unstuck.
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes