快速排序在枢轴的确定上有很多方式,该篇只是讨论基本的快速排序思想,默认首个元素即为枢轴。待日后对其进行学习补充。欢迎讨论学习。凌晨两点写完的稿,难免会有错别字,敬请谅解。
原始数据:
左边 40 56 1 9 12 19 右边
一趟排序过程:
一趟排序完成:
19 12 1 9 40 56
根据上述排序过程,写出下列代码:
#include<iostream>
#include<cstdio>
using namespace std;
void quickSort(int *arr, int begin, int end);
int getIndex(int *arr, int low, int high);
void show(int *arr, int N){
for(int i = 0; i < N; i ++){
cout<<arr[i]<<"\t";
}
cout<<endl;
}
int main(void){
int arr[6] = { 40, 56, 1, 9, 12, 19};
cout<<"原始数组:"<<endl;
show( arr, 6);
cout<<endl<<"排序过程:"<<endl<<endl;
quickSort( arr, 0, 5);
cout<<"排序过后的数组:"<<endl;
show( arr, 6);
return 0;
}
void quickSort(int *arr, int begin, int end){
if(begin >= end) return;
// 获取上一次排序枢轴位置(即就是 排序位置确定的元素位置)
int index = getIndex( arr, begin, end);
cout<<"完成1次排序后的数组结果:"<<endl;
show(arr,6);
cout<<endl<<endl;
//对枢轴左边的数据进行递归排序
quickSort( arr, begin, index - 1);
//对枢轴右边的数据进行递归排序
quickSort( arr, index + 1, end);
}
int getIndex(int *arr, int low, int high){
int temp = arr[low];
while(low < high){
// 从最右端开始向左找到小于枢轴的元素
while(low < high && arr[high] >= temp){
high --;
}
arr[low] = arr[high];//将 high指针 指向的小于枢轴的元素交换到 low指针 所指的位置
// 打印数组元素的变化情况
cout<<"low: "<<low<<" high: "<<high<<" 元素变化:";
show(arr,6);
// 从最右端开始想右找到大于枢轴的元素
while(low < high && arr[low] <= temp){
low ++;
}
arr[high] = arr[low];//将 low指针 指向的大于枢轴的元素交换到 high指针 所指的位置
// 打印数组元素的变化情况
cout<<"low: "<<low<<" high: "<<high<<" 元素变化:";
show(arr,6);
}
cout<<"将 枢轴:"<<temp<<" 替代找到的位置的元素:"<<endl;// 为了显示过程是否正确
arr[low] = temp;
return low;
}
运行结果: