快速排序:
思路:
1.把数组第一个元素作为主元
2.找主元位置(主元左边的数都比主元小,主元右边的数都比主元大,左右两边数字的存放顺序不用在意,因为还会递归进去继续找主元,然后分割)
3.从主元位置分割,左、右两边分别继续快排(找主元位置,分割)
4.直到最小下标 = 最大下标(代表着分割的此数组只剩下这一个元素,不再递归)
代码(C语言):
#include <stdio.h>
void quickSort(int* a, int low, int high);
int findPos(int* a, int low, int high);
int main(void) {
int i;
int array[] = { 9, 6, -1, -124, 0, -99, -5};
quickSort(array, 0, 6);
for (i = 0; i < 7; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
void quickSort(int* a, int low, int high) {
int pos;
if (low < high) {
pos = findPos(a, low, high);
quickSort(a, low, pos - 1);
quickSort(a, pos + 1, high);
}
}
int findPos(int * a, int low, int high) {
int val = a[low];
while (low < high) {
while (low < high && a[high] >= val)
--high;
a[low] = a[high];`
while (low < high && a[low] <= val)
++low;
a[high] = a[low];
a[low] = val;
}
return low;
}