Last active
November 5, 2017 03:58
-
-
Save tacigar/235fefa5e11abda512a697c3e68adb23 to your computer and use it in GitHub Desktop.
普通のクイックソートなり.
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
#include <stdio.h> | |
void print_array(int * array, int size) { | |
int i = 0; | |
printf("{ "); | |
while (1) { | |
printf("%d", array[i]); | |
if (++i >= size) { | |
printf("}\n"); | |
break; | |
} else { | |
printf(","); | |
} | |
} | |
} | |
int pivot(int *array, int begin, int end) { | |
int i = begin + 1; | |
while (i <= end && array[begin] == array[i]) i++; | |
if (i > end) | |
return -1; | |
if (array[begin] >= array[i]) | |
return begin; | |
return i; | |
} | |
int partition(int *array, int begin, int end, int pivot_value) { | |
int left = begin, right = end; | |
while (left <= right) { | |
while (left <= end && array[left] < pivot_value) left++; | |
while (right >= begin && array[right] >= pivot_value) right--; | |
if (left > right) break; | |
else { | |
int temp = array[left]; | |
array[left] = array[right]; | |
array[right] = temp; | |
left++; right--; | |
} | |
} | |
return left; | |
} | |
void quick_sort(int *array, int begin, int end) { | |
if (begin == end) return; | |
int pivot_index = pivot(array, begin, end); | |
if (pivot_index != -1) { | |
int partition_point = partition(array, begin, end, array[pivot_index]); | |
quick_sort(array, begin, partition_point -1); | |
quick_sort(array, partition_point, end); | |
} | |
} | |
int main(void) { | |
int i; | |
int tests[4][5] = { | |
{ 1, 2, 3, 4, 5 }, | |
{ 2, 3, 4, 5, 1 }, | |
{ 4, 5, 3, 2, 3 }, | |
{ 5, 4, 3, 1, 1 } | |
}; | |
for (i = 0; i < 4; i++) { | |
quick_sort(tests[i], 0, 4); | |
print_array(tests[i], 5); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment