└── Quick sort /Quick sort: -------------------------------------------------------------------------------- 1 | // Quick sort in C 2 | 3 | #include 4 | 5 | // function to swap elements 6 | void swap(int *a, int *b) { 7 | int t = *a; 8 | *a = *b; 9 | *b = t; 10 | } 11 | 12 | // function to find the partition position 13 | int partition(int array[], int low, int high) { 14 | 15 | // select the rightmost element as pivot 16 | int pivot = array[high]; 17 | 18 | // pointer for greater element 19 | int i = (low - 1); 20 | 21 | // traverse each element of the array 22 | // compare them with the pivot 23 | for (int j = low; j < high; j++) { 24 | if (array[j] <= pivot) { 25 | 26 | // if element smaller than pivot is found 27 | // swap it with the greater element pointed by i 28 | i++; 29 | 30 | // swap element at i with element at j 31 | swap(&array[i], &array[j]); 32 | } 33 | } 34 | 35 | // swap the pivot element with the greater element at i 36 | swap(&array[i + 1], &array[high]); 37 | 38 | // return the partition point 39 | return (i + 1); 40 | } 41 | 42 | void quickSort(int array[], int low, int high) { 43 | if (low < high) { 44 | 45 | // find the pivot element such that 46 | // elements smaller than pivot are on left of pivot 47 | // elements greater than pivot are on right of pivot 48 | int pi = partition(array, low, high); 49 | 50 | // recursive call on the left of pivot 51 | quickSort(array, low, pi - 1); 52 | 53 | // recursive call on the right of pivot 54 | quickSort(array, pi + 1, high); 55 | } 56 | } 57 | 58 | // function to print array elements 59 | void printArray(int array[], int size) { 60 | for (int i = 0; i < size; ++i) { 61 | printf("%d ", array[i]); 62 | } 63 | printf("\n"); 64 | } 65 | 66 | // main function 67 | int main() { 68 | int data[] = {8, 7, 2, 1, 0, 9, 6}; 69 | 70 | int n = sizeof(data) / sizeof(data[0]); 71 | 72 | printf("Unsorted Array\n"); 73 | printArray(data, n); 74 | 75 | // perform quicksort on data 76 | quickSort(data, 0, n - 1); 77 | 78 | printf("Sorted array in ascending order: \n"); 79 | printArray(data, n); 80 | } 81 | --------------------------------------------------------------------------------