快排是所有内部排序算法中平均性能最优的排序算法,其基本思想是基于分治法。 本文首先实现了一个快排的基本程序,然后列举了一个关于快排的应用:最小的k个数。
理论部分就不说了,直接上代码。程序中从无重复数字数组、带有重复数字的数组、单个数字的数组和空数组几方面测试了代码的完整性。 代码:
#include<iostream>#include<vector>using namespace std;void QuickSort(vector<int> &array, int low, int high); //将数组[low high]区间排序int partition(vector<int> &array, int low, int high); //将数组[low high]区间以返回值位置划分为两部分,且通过调整数组中元素的位置使前一部分的元素值均比返回值位置的元素小,后一部分则相反。void test(vector<int> &array);int main(){ vector<int> v1 = { 3, 8, 7, 1, 2, 5, 6, 4 }; vector<int> v2 = { 3, 8, 6, 1, 2, 5, 6, 4 }; vector<int> v3 = { 3 }; vector<int> v4 = {}; test(v1); //功能测试 test(v2); test(v3); //边界测试 test(v4); //负面测试 return 0;}void test(vector<int> &array) { unsigned int lengthOfArray = array.size(); cout << "The original order of the array is:" << endl; for (int i = 0; i<lengthOfArray; i++) { cout << array.at(i) << ' '; } cout << endl; if (0 == lengthOfArray) cout << "The array is empty." << endl; else { QuickSort(array, 0, lengthOfArray - 1); cout << "The sorted order of the array is:" << endl; for (int i = 0; i < lengthOfArray; i++) cout << array.at(i) << ' '; cout << endl; } cout << endl;}void QuickSort(vector<int> &array, int low, int high) { if (low<high) { int pivotpos = partition(array, low, high); QuickSort(array, low, pivotpos - 1); QuickSort(array, pivotpos + 1, high); }}int partition(vector<int> &array, int low, int high) { int pivot = array.at(low); //选取数组low位置的元素作为枢轴值,进行划分 while (low < high) { while (low < high && array.at(high) >= pivot) --high; array.at(low) = array.at(high); while (low < high && array.at(low) <= pivot) ++low; array.at(high) = array.at(low); } array.at(low) = pivot; return low;}题目:输入n个整数,找出其中最小的k个数。例如输入4、5、1、6、2、7、3、8
这8个数字,则最小的4个数字是1、2、3、4
。 此问题有多种解法,这里使用了基于快排一次排序分治的思想来解决此问题。
新闻热点
疑难解答