1.代码
#include "stdio.h"
//快速排序
void quickSort(int arr[],int left, int right){
int ch[3] = {0};
int tempLeft = left;
int tempRight = right;
//选取最左边的为基准元素
int temp = arr[left];
int compareRight = 1;
while (left != right) {
if (compareRight == 1) {
//temp和右边的数比
if(temp > arr[right]){
arr[left] = arr[right];
left++;
compareRight = 0;
}else{
right--;
}
}else{
//temp和左边的数比
if (temp < arr[left]) {
arr[right] = arr[left];
right--;
compareRight = 1;
}else{
left++;
}
}
}
arr[left] = temp;
//排序基准元素左边的
if (tempLeft < (left-1)) {
quickSort(arr, tempLeft, left-1);
}
//排序基准元素右边的
if (tempRight > left+1) {
quickSort(arr, left+1, tempRight);
}
}
int main()
{
int numArr[] = {3,5,4,6,2,45,22};
int len = sizeof(numArr)/sizeof(int);
quickSort(numArr,0,len-1);
for (int i = 0; i < len; i++) {
printf("%d\n",numArr[i]);
}
}
打印结果:
2
3
4
5
6
22
45
Program ended with exit code: 0