Created
March 3, 2020 15:04
-
-
Save pedrominicz/cf2a0491b155a930cccd66144d5405ec to your computer and use it in GitHub Desktop.
Quick sort.
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> | |
#define swap(x, y) { int tmp = x; x = y; y = tmp; } | |
void quick_sort(int n, int array[]) { | |
if(n < 2) return; | |
int i = 0; | |
int j = n - 2; | |
while(i <= j) { | |
while(i <= j && array[i] <= array[n - 1]) ++i; | |
while(j >= i && array[j] > array[n - 1]) --j; | |
if(i < j) { | |
swap(array[i], array[j]); | |
} | |
} | |
swap(array[i], array[n - 1]); | |
quick_sort(i, array); | |
quick_sort(n - i, array + i); | |
} | |
#define test(...) \ | |
{ \ | |
int array[] = { __VA_ARGS__ }; \ | |
int size = sizeof(array) / sizeof(int); \ | |
quick_sort(size, array); \ | |
for(int i = 0; i < size; ++i) { \ | |
printf("%d ", array[i]); \ | |
} \ | |
printf("\n"); \ | |
} | |
int main(void) { | |
test(1, 2, 6, 9, 8, 3, 10, 7, 5, 4); | |
test(7, 10, 2, 9, 1, 8, 5, 4, 6, 3); | |
test(5, 10, 3, 8, 6, 4, 7, 1, 9, 2); | |
test(3, 8, 10, 1, 9, 5, 7, 6, 2, 4); | |
test(2, 1, 8, 5, 4, 10, 7, 6, 9, 3); | |
test(6, 8, 3, 9, 5, 7, 2, 1, 10, 4); | |
test(1, 2, 6, 5, 9, 4, 8, 3, 7, 10); | |
test(1, 2, 8, 6, 5, 7, 10, 4, 3, 9); | |
test(3, 5, 4, 6, 8, 2, 10, 9, 7, 1); | |
test(9, 4, 3, 6, 1, 7, 2, 10, 8, 5); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment