Skip to content

Instantly share code, notes, and snippets.

@josephok
Created June 14, 2016 04:58
Show Gist options
  • Save josephok/9c2407fc6afb31fbab613bf44ff93bf7 to your computer and use it in GitHub Desktop.
Save josephok/9c2407fc6afb31fbab613bf44ff93bf7 to your computer and use it in GitHub Desktop.
quick sort
#include <stdio.h>
void quicksort(int *arr, int low, int high)
{
int pivot, i, j, temp;
if(low < high) {
pivot = low; // select a pivot element
i = low;
j = high;
while(i < j) {
// increment i till you get a number greater than the pivot element
while(arr[i] <= arr[pivot] && i <= high)
i++;
// decrement j till you get a number less than the pivot element
while(arr[j] > arr[pivot] && j >= low)
j--;
// if i < j swap the elements in locations i and j
if(i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// when i >= j it means the j-th position is the correct position
// of the pivot element, hence swap the pivot element with the
// element in the j-th position
temp = arr[j];
arr[j] = arr[pivot];
arr[pivot] = temp;
// Repeat quicksort for the two sub-arrays, one to the left of j
// and one to the right of j
quicksort(arr, low, j-1);
quicksort(arr, j+1, high);
}
}
int main(int argc, char const *argv[]) {
int array[] = {99, 98, 97, 96, 95, -100, 100, 0};
int n = sizeof(array) / sizeof(int);
quicksort(array, 0, n - 1);
for (size_t i = 0; i < n; i++) {
printf("%d\n", array[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment