Skip to content

Instantly share code, notes, and snippets.

@NoraCodes
Created August 23, 2015 15:40
Show Gist options
  • Save NoraCodes/e1b7f35ea8b6b19274a7 to your computer and use it in GitHub Desktop.
Save NoraCodes/e1b7f35ea8b6b19274a7 to your computer and use it in GitHub Desktop.
C implementation of quicksort which colors the values being swapped for instructional purpouses.
/*
Algorithm Practice: Quicksort
*/
#include <stdio.h>
#define ARRAY_LENGTH 32
int array[ARRAY_LENGTH]; // The array to be sorted
int setup(int array[]){
// Fill the array with random numbers.
int i;
for (i=0; i < ARRAY_LENGTH; i++) {
array[i] = rand() % ARRAY_LENGTH;
}
}
void report(int array[], int len){
// Report the contents of an array
int i;
for (i = 0; i < len; i++){
printf("%02d ", array[i]);
}
printf("\n");
}
void creport(int array[], int len, int ilow, int ihigh){
// Report the contents of an array
int i;
for (i = 0; i < len; i++){
if (i == ilow){
printf("\033[32m%02d\033[0m ", array[i]);
} else {
if (i == ihigh){
printf("\033[33m%02d\033[0m ", array[i]);
} else {
printf("%02d ", array[i]);
}
}
}
printf(" (%02d and %02d) \n", array[ilow], array[ihigh]);
}
void quicksort(int lbound, int rbound, int array[]){
int i, j, pivot;
i = lbound;
j = rbound;
int tmp;
pivot = array[(lbound + rbound) / 2];
while (i <= j){
while (array[i] < pivot){
i++;
} // At this point, we have found a misplaced number; Now to find something to swap it with.
while (array[j] > pivot){
j--;
}
// Now, we swap the two numbers:
if (i <= j){
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
creport(array, ARRAY_LENGTH, i, j);
i++;
j--;
}
};
if (lbound < j){
quicksort(lbound, j, array);
}
if (i < rbound){
quicksort(i, rbound, array);
}
}
int main(){
// Setup and sort the array.
printf("Setting up array...\n");
setup(array);
report(array, ARRAY_LENGTH);
printf("Done, sorting array...\n");
quicksort(0, ARRAY_LENGTH-1, array);
printf("Done sorting.\n");
report(array, ARRAY_LENGTH);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment