From b9b7a4ef7ee071edd7a07788a62f6d81871dfb19 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Wed, 15 Jun 2022 10:50:11 +0530 Subject: add qsort and 4.11 --- qsort.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 qsort.c (limited to 'qsort.c') diff --git a/qsort.c b/qsort.c new file mode 100644 index 0000000..dbf234b --- /dev/null +++ b/qsort.c @@ -0,0 +1,77 @@ +#include + +void printia(int array[], int len); +void qsort(int array[], int left, int right); +void swap(int array[], int i, int j); + +int +main(void) +{ + /* 0 1 2 3 4 5 6 7 8 9*/ + int array[10] = {9, 6, 1, 5, 3, 7, 0, 4, 2, 8}; + + printf("c> 0 1 2 3 4 5 6 7 8 9\n"); + printia(array, sizeof(array)/sizeof(int)); + qsort(array, 0, sizeof(array)/sizeof(int)-1); + printia(array, sizeof(array)/sizeof(int)); + + return 0; +} + +void +printia(int array[], int len) +{ + int i; + + printf("a> "); + + for (i = 0; i < len; i++) + printf("%d ", array[i]); + + printf("\n"); +} + +void +qsort(int array[], int left, int right) +{ + int i, last; + + if (left >= right) + return; + + printf("1> array[%d] <=> array[%d] | %d <=> %d\n", left, (left+right)/2, array[left], array[(left+right)/2]); + swap(array, left, (left+right)/2); + printia(array, 10); + last = left; + + for (i = left+1; i <= right; i++) + if (array[i] < array[left]) { + printf("2> array[%d] <=> array[%d] | %d <=> %d\n", last+1, i, array[last+1], array[i]); + swap (array, ++last, i); + printia(array, 10); + } + printf("s> |----------+-------|\n"); + + printf("3> array[%d] <=> array[%d] | %d <=> %d\n", left, last, array[left], array[last]); + swap(array, left, last); + printia(array, 10); + + qsort (array, left, last-1); + qsort(array, last+1, right); + printf("s> |----------------+-------|\n"); + +} + +void +swap(int array[], int i, int j) +{ + int temp; + + if (i == j) + printf("s> |----------+-------|\n"); + + temp = array[i]; + + array[i] = array[j]; + array[j] = temp; +} -- cgit v1.2.3