/* * Quicksort implementation example */ #include #define MAXSIZE 8 void quicksort(int x[], int first, int last){ int pivot, i, j, s; if (first < last){ pivot = first; i = first; j = last; /* Sort in ascending order */ while(i < j){ while((x[i] <= x[pivot]) && (i < last) ) i++; while(x[j] > x[pivot]) j--; if(i < j){ s = x[i]; x[i] = x[j]; x[j] = s; } } s = x[pivot]; x[pivot] = x[j]; x[j] = s; quicksort(x, first, j-1); quicksort(x, j+1, last); } } void bubble_sort(int n, int list[]) { int i, j, s; for (i = 0 ; i < n - 1; i++) { for (j = 0 ; j < n - i - 1; j++) { /* Sort in ascending order */ if (list[j] > list[j+1]) { /* swap */ s = list[j]; list[j] = list[j+1]; list[j+1] = s; } } } } int main(void) { int a[MAXSIZE], n = MAXSIZE, i; /* * Worst case scenario - a list in descending order */ printf("Original list in descending order:\n"); for (i = 0 ; i < n ; i++) { a[i] = n - i; printf("%3d\n", a[i]); } /*bubble_sort(n, a);*/ quicksort(a, 0, n-1); printf("Sorted list in ascending order:\n"); for (i = 0 ; i < n ; i++) { printf("%3d\n", a[i]); } return 0; }