这是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;
else
bIsContinue = false;
}
return 0;
}