Write a C program for Quick Sort.

Quicksort(A,p,r):

	if p < r
	 q = Partition(A,p,r)
	 Quicksort(A,p,q - 1)
	 Quicksort(A,q + 1,r)

Partition(A,p,r):
	i = p-1
	for j = p to r-1
	 if A[j] ≤ A[r]
	 i = i + 1

	 exchange A[i] with A[j]
	exchange A[i+1] with A[r]
	return i+1

Figure: Quick Sort

#include <stdio.h>
 
void print_array(int size, int array[]) {
    for (int pos = 0; pos < size; pos += 1) {
        printf("%d%s", array[pos], pos + 1 == size ? "" : " ");
    }
    printf("\n");
}
 
void quick_sort (int size, int array[], int left, int right) {
    //! quicksort = showSort(array, cursors=[left, right, i, j], dim=size, thresholds=[pivot])
    if (right <= left)
        return;
    int pivot = array[right];
    int i = left;
    int j = right;
    while (1) {
        while (array[i] < pivot)
            i += 1;
        while (pivot < array[j])
            j -= 1;
        if (i >= j) {
            break;
        }
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        i += 1;
        j -= 1;
    }
    quick_sort(size, array, left, i - 1);
    quick_sort(size, array, i, right);
}
 
int main() {
    //! quicksort = showSort(array, dim=n)
    int array[] = {4, 2, 1, 2, 3, 2, 1, 0, 1};
    int n = sizeof array / sizeof *array;
    quick_sort(n, array, 0, n - 1);
    print_array(n, array);
    return 0;
} 

0 1 1 1 2 2 2 3 4

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.