Skip to content

Instantly share code, notes, and snippets.

@marodrig
Created April 21, 2014 06:28
Show Gist options
  • Save marodrig/11133965 to your computer and use it in GitHub Desktop.
Save marodrig/11133965 to your computer and use it in GitHub Desktop.
Quicksort implementation using a 3 way partition. In C
#include <stdio.h>
#include <stdlib.h>
void exchange_values(int input_array[], int left_index, int right_index){
int temp_value = input_array[left_index];
input_array[left_index] = input_array[right_index];
input_array[right_index] = temp_value;
return;
}
int is_sorted(int input_array[], int size_of_array){
int i ;
for(i = 0; i < size_of_array - 1; i ++){
if(input_array[i] > input_array[i+1]){
return -1;
}
}
return 1;
}
void quick_sort(int input_array[], int bottom_bound, int upper_bound){
if(upper_bound <= bottom_bound){
return;
}
int lowest_index = bottom_bound;
int i = bottom_bound + 1;
int top_index = upper_bound;
int pivot = input_array[bottom_bound];
while(i <= top_index){
if(input_array[i] < pivot){
exchange_values(input_array, lowest_index++, i++);
}else if(input_array[i] >= pivot){
exchange_values(input_array, i, top_index--);
}else{
i++;
}
}
quick_sort(input_array, bottom_bound, lowest_index - 1);
quick_sort(input_array, top_index + 1, upper_bound);
}
int main(int argc, char* argv[]){
/* code */
int size_of_array = 1000000;
int input_array[size_of_array];
int i;
for(i = 0; i < size_of_array; i++){
input_array[i] = rand() % 10000;
}
quick_sort(input_array, 0, size_of_array);
if(is_sorted(input_array, size_of_array) > 0){
printf("Is sorted\n");
}else{
printf("Not sorted\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment