Skip to content

Instantly share code, notes, and snippets.

@pczajkowski
Created December 27, 2017 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pczajkowski/98a45f7d72963d987aac4874a3322aa0 to your computer and use it in GitHub Desktop.
Save pczajkowski/98a45f7d72963d987aac4874a3322aa0 to your computer and use it in GitHub Desktop.
Sorting algorithms in C
void bubbleSort(int list[], int listLength) {
int doItAgain = 0;
for (int i = 0; i < listLength; i++) {
int thisValue = list[i];
int nextValue = (i + 1 < listLength) ? list[i+1] : INT_MAX;
if (nextValue < thisValue) {
list[i] = nextValue;
list[i+1] = thisValue;
doItAgain = 1;
}
}
if (doItAgain) bubbleSort(list, listLength);
}
void gnomeSort(int list[], int listLength) {
int pos = 0;
while (pos < listLength) {
if (pos == 0 || list[pos] >= list[pos - 1])
pos += 1;
else {
int temp = list[pos];
list[pos] = list[pos - 1];
list[pos - 1] = temp;
pos -= 1;
}
}
}
void gnomeSortOpt(int list[], int upperBound) {
int pos = upperBound;
while (pos > 0 && list[pos - 1] > list[pos]) {
int temp = list[pos];
list[pos] = list[pos - 1];
list[pos - 1] = temp;
pos -= 1;
}
}
void optimizedGnomeSort(int list[], int listLength) {
for (int pos = 1; pos < listLength; pos++)
gnomeSortOpt(list, pos);
}
void swap(int list[], int i, int j) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
int partition(int list[], int lo, int hi) {
int pivot = list[hi];
int i = lo - 1;
for (int j = lo; j <= hi - 1; j++) {
if (list[j] <= pivot) {
i++;
swap(list, i, j);
}
}
swap(list, i+1, hi);
return i + 1;
}
void quicksort(int list[], int lo, int hi) {
if (lo < hi) {
int p = partition(list, lo, hi);
quicksort(list, lo, p-1);
quicksort(list, p+1, hi);
}
}
void selectionSort(int list[], int listLength) {
for (int i = 0; i < listLength; i++) {
int currentMinIndex = i;
for (int x = currentMinIndex + 1; x < listLength; x++) {
if (list[x] < list[currentMinIndex]) currentMinIndex = x;
}
if (currentMinIndex != i) {
int oldMinValue = list[i];
list[i] = list[currentMinIndex];
list[currentMinIndex] = oldMinValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment