Created
July 5, 2013 17:48
-
-
Save ser1zw/5936116 to your computer and use it in GitHub Desktop.
C言語でクイックソートの練習
This file contains 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
// -*- mode: c; coding: utf-8 -*- | |
#include <stdio.h> | |
void quicksort_internal(int array[], int left, int right, int (*test_func)(int, int)) { | |
int pivot; | |
int i, j, tmp; | |
if (left >= right) { | |
return; | |
} | |
i = left; | |
j = right; | |
pivot = array[i]; | |
while (1) { | |
for (; i < right && test_func(array[i], pivot) > 0; i++); | |
for (; j >= left && test_func(array[j], pivot) < 0; j--); | |
if (i >= j) { | |
break; | |
} | |
tmp = array[i]; | |
array[i] = array[j]; | |
array[j] = tmp; | |
i++; | |
j--; | |
} | |
quicksort_internal(array, left, i - 1, test_func); | |
quicksort_internal(array, j + 1, right, test_func); | |
} | |
void quicksort(int array[], int size, int (*test_func)(int, int)) { | |
quicksort_internal(array, 0, size - 1, test_func); | |
} | |
int asc(int a, int b) { | |
return (a == b) ? 0 : (a < b) ? 1 : -1; | |
} | |
int desc(int a, int b) { | |
return (a == b) ? 0 : (a > b) ? 1 : -1; | |
} | |
int main(int argc, char *argv[]) { | |
int a[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9 }; | |
int i; | |
int size = sizeof(a) / sizeof(a[0]); | |
puts("Array:"); | |
for (i = 0; i < size; i++) { | |
printf("%d ", a[i]); | |
} | |
puts(""); | |
puts("Asc:"); | |
quicksort(a, size, asc); | |
for (i = 0; i < size; i++) { | |
printf("%d ", a[i]); | |
} | |
puts(""); | |
puts("Desc:"); | |
quicksort(a, size, desc); | |
for (i = 0; i < size; i++) { | |
printf("%d ", a[i]); | |
} | |
puts(""); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment