|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +void swap(int *x,int *y); |
| 5 | +int choose_pivot(int i,int j ); |
| 6 | +void quicksort(int list[],int m,int n); |
| 7 | +void display(int list[],const int n); |
| 8 | + |
| 9 | +void main() |
| 10 | +{ |
| 11 | + const int SIZE = 10; |
| 12 | + int list[SIZE]; |
| 13 | + |
| 14 | + int i = 0; |
| 15 | + |
| 16 | + /* generates random numbers and fill the list */ |
| 17 | + for(i = 0; i < SIZE; i++ ) |
| 18 | + list[i] = rand(); |
| 19 | + |
| 20 | + printf("The list before sorting is:\n"); |
| 21 | + display(list,SIZE); |
| 22 | + |
| 23 | + /* sort the list using quicksort algorithm */ |
| 24 | + quicksort(list,0,SIZE-1); |
| 25 | + |
| 26 | + printf("The list after sorting:\n"); |
| 27 | + display(list,SIZE); |
| 28 | +} |
| 29 | + |
| 30 | +void swap(int *x,int *y) |
| 31 | +{ |
| 32 | + int temp; |
| 33 | + temp = *x; |
| 34 | + *x = *y; |
| 35 | + *y = temp; |
| 36 | +} |
| 37 | + |
| 38 | +int choose_pivot(int i,int j ) |
| 39 | +{ |
| 40 | + return((i+j) /2); |
| 41 | +} |
| 42 | + |
| 43 | +void quicksort(int list[],int m,int n) |
| 44 | +{ |
| 45 | + int key,i,j,k; |
| 46 | + if( m < n) |
| 47 | + { |
| 48 | + k = choose_pivot(m,n); |
| 49 | + swap(&list[m],&list[k]); |
| 50 | + key = list[m]; |
| 51 | + i = m+1; |
| 52 | + j = n; |
| 53 | + while(i <= j) |
| 54 | + { |
| 55 | + while((i <= n) && (list[i] <= key)) |
| 56 | + i++; |
| 57 | + while((j >= m) && (list[j] > key)) |
| 58 | + j--; |
| 59 | + if( i < j) |
| 60 | + swap(&list[i],&list[j]); |
| 61 | + } |
| 62 | + /* swap two elements */ |
| 63 | + swap(&list[m],&list[j]); |
| 64 | + |
| 65 | + /* recursively sort the lesser list */ |
| 66 | + quicksort(list,m,j-1); |
| 67 | + quicksort(list,j+1,n); |
| 68 | + } |
| 69 | +} |
| 70 | +void display(int list[],const int n) |
| 71 | +{ |
| 72 | + int i; |
| 73 | + for(i=0; i<n; i++) |
| 74 | + printf("%d\t",list[i]); |
| 75 | +} |
| 76 | + |
0 commit comments