diff options
Diffstat (limited to 'c/dataStructure/sorting/quickSort.c')
-rwxr-xr-x | c/dataStructure/sorting/quickSort.c | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/c/dataStructure/sorting/quickSort.c b/c/dataStructure/sorting/quickSort.c new file mode 100755 index 0000000..2904b48 --- /dev/null +++ b/c/dataStructure/sorting/quickSort.c @@ -0,0 +1,63 @@ +#include<stdio.h> +#include<stdlib.h> +#include<time.h> + +#define SIZE 10 + +void swap(int * a, int * b) +{ + int tmp = *a; + *a = *b; + *b = tmp; +} + +void generateRandom(int * arr, int n) +{ + time_t sr; + srand(sr); + + for(int i = 0; i < n; i++) + arr[i] = rand() % 100; +} + +int partition(int * arr, int low, int high) +{ + int i,j; + for (i = low, j = low; i < high; i++) + if (arr[i] < arr[high]) + { + swap(&arr[i],&arr[j]); + j++; + } + swap(&arr[high],&arr[j]); + + return j; +} + +void quickSort(int * arr, int low, int high) +{ + if (low < high) + { + int pivot = partition(arr,low,high); + quickSort(arr,low, pivot - 1); // sort left + quickSort(arr,pivot + 1, high); + } +} + +int main(void) +{ + int arr[SIZE]; + generateRandom(arr,SIZE); + + for(int i = 0; i < SIZE; i++) + printf("%3d",*(arr+i)); + putchar('\n'); + + quickSort(arr,0,SIZE - 1); + + for (int i = 0; i < SIZE; i++) + printf("%3d",arr[i]); + putchar('\n'); + + return 0; +} |