微软面试题:三路划分快速排序---针对重复关键字的改进

来源:互联网 发布:java多线程发送短信 编辑:程序博客网 时间:2024/05/29 08:08

这是2012年微软实习生招聘的面试题,可惜的是本人没有通过,但是这道题当时是做出来了

题目:改写partition算法。要求:一次partition之后,小于基准元素key的数在左边,等于key的在中间,大于key的在右边

思路:参照算法导论上的思想,做出改进:i指向小于基准元素的序列的末尾,j指向等于基准元素的序列的末尾,k指向当前遍历到的元素,说到这里应该可以了

程序c++实现:

 #include <iostream> #include <cstdlib> using namespace std; void print(int *arr, int start, int end) {for (int i = start; i <= end; ++i)cout << arr[i] << ' ';cout << endl; } void randData(int *arr, int start, int end) {for (int i = start; i <= end; ++i)arr[i] = rand() % 20; cout << "the old array:\n ";print(arr, start, end); } int partition(int *arr, int start, int end){cout << "before partition:" << endl;print(arr, start, end);//打印一次partition之前的数组int key = arr[end];int i, j, k;i = start - 1;//i指向小于基准元素的序列的末尾j = i;//j指向等于基准元素的序列的末尾for(k = start; k != end; ++k)//k指向当前遍历到的元素{if (arr[k] < key){swap(arr[++j], arr[k]);swap(arr[j], arr[++i]);}else if (arr[k] == key){swap(arr[++j], arr[k]);}}swap(arr[++j], arr[end]);cout << "after partition:" << endl;print(arr, start, end);//打印一次partition之后的数组cout << endl;return j;}void quickSort(int *arr, int start, int end) {if (start < end){int k = partition(arr, start, end);quickSort(arr, start, k - 1);quickSort(arr, k + 1, end);} } int main() {bool bIsContinue = true;char ch = 'n';const int Len = 10;int arr[Len];while (true == bIsContinue){randData(arr, 0, Len - 1);quickSort(arr, 0, Len - 1);cout << "the new array:\n ";print(arr, 0, Len - 1);cout << "please input yes or no" << endl;cin >> ch;if (ch == 'y' || ch == 'Y')bIsContinue = true;elsebIsContinue = false;}    return 0; }  


原创粉丝点击