Skip to content

Instantly share code, notes, and snippets.

@gyaikhom
Last active August 29, 2015 14:03
Show Gist options
  • Save gyaikhom/e2b251963518bbc85d6a to your computer and use it in GitHub Desktop.
Save gyaikhom/e2b251963518bbc85d6a to your computer and use it in GitHub Desktop.
Implementation of Single-Pivot Quick Sorting.
/**
* Copyright 2014 Gagarine Yaikhom (MIT License)
*
* Implementation of Single-Pivot Quick Sorting.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void print_array(const int *a, int size) {
int i;
for (i = 0; i < size; ++i)
printf("%d ", a[i]);
printf("\n");
}
void quick_sort(int *a, int size) {
int i, j, t, pivot;
if (size < 2)
return;
pivot = a[rand() % size];
i = 0;
j = size - 1;
while (i < j) {
while (a[i] < pivot) ++i;
while (a[j] > pivot) --j;
if (i < j) {
t = a[j];
a[j] = a[i];
a[i] = t;
}
}
quick_sort(a, i);
quick_sort(&a[i + 1], size - i - 1);
}
int main(void) {
int a[] = {5, 3, 8, 2, 7, 6, 9}, size;
size = sizeof(a) / sizeof(a[0]);
printf("Unsorted: ");
print_array(a, size);
srand(time(0));
quick_sort(a, size);
printf(" Sorted: ");
print_array(a, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment