快速排序_C語言_數組 include void quickSort(int , int, int); int searchPos(int , int, int); int main(int argc, const char argv[]) { //定義亂序數組 int a[10] = {9, 3, ...
快速排序_C語言_數組
#include <stdio.h>
void quickSort(int *, int, int);
int searchPos(int *, int, int);
int main(int argc, const char * argv[]) {
//定義亂序數組
int a[10] = {9, 3, 4, 6, 1, 2, 7, 8, 5, 0};
//排序前輸出:
printf("亂序:\n");
for (int i = 0; i < 10; i++) {
printf("%d ",a[i]);
}
printf("\n\n");
//排序
quickSort(a, 0, 10);
//排序後輸出:
printf("順序:\n");
for (int i = 0; i < 10; i++) {
printf("%d ",a[i]);
}
printf("\n");
return 0;
}
void quickSort(int *a, int low, int height) {
int pos;
if (low < height) {
pos = searchPos(a, low, height);
quickSort(a, low, pos - 1);
quickSort(a, pos + 1, height);
}
}
int searchPos(int *a, int low, int height) {
int val = a[low];
while (low < height) {
while (low < height && a[height] > val) {
height --;
}
a[low] = a[height];
while (low < height && a[low] < val) {
low ++;
}
a[height] = a[low];
}
a[low] = val;
return low;
}