-
-
Save mhansen/4203749 to your computer and use it in GitHub Desktop.
Three sorting algorithms, in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
void swap(char* a, char* b) { | |
char t = *a; | |
*a = *b; | |
*b = t; | |
} | |
void bubblesort(char* s, int n) { | |
int i, j; | |
for (i = 0; i < n; i++) { | |
for (j = 0; j < n-1; j++) { | |
if (s[j] > s[j+1]) { | |
swap(&s[j], &s[j+1]); | |
} | |
} | |
} | |
} | |
void selectionsort(char* b, int n) { | |
if (n < 1) return; | |
int j; | |
for (j = 0; j < n - 1; j++) { | |
int si = j; | |
int i; | |
for (i = j; i < n; i++) { | |
if (b[i] < b[si]) { | |
si = i; | |
} | |
} | |
swap(&b[j], &b[si]); | |
} | |
} | |
void qsort(char* b, int n) { | |
if (n <= 1) return; | |
int pivot = n / 2; // deal with it. | |
swap(&b[pivot], &b[n-1]); | |
int s = 0; | |
int i; | |
for (i = 0; i < n - 1; i++) { | |
if (b[i] < b[n - 1]) { | |
swap(&b[s], &b[i]); | |
s++; | |
} | |
} | |
swap(&b[n-1], &b[s]); | |
qsort(b, s); | |
qsort(b+s+1, (n-s)-1); | |
} | |
int main(int argc, char** argv) { | |
int i; | |
for (i = 1; i < argc; i++) { | |
qsort(argv[i], strlen(argv[i])); | |
printf("%s\n", argv[i]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment