您的位置:首页 > 编程语言 > C语言/C++

c++实现快速排序(挖坑填数版)

2012-08-23 10:42 351 查看
无疑这种方法比本来的方法更加快捷,减少了内存开销,直接在原数组进行排序

#include <iostream>
using namespace std;
//采用挖坑法实现快速排序
template <typename T>
int quickSort2(T *const t, const int begin,const int end)
{
if(begin >= end)
{
return 0;
}
T temp = t[begin];
int left = begin;
int right = end;
while(left < right)
{
while(t[right] > temp && left < right)
{
right--;
}
if(left != right)
{
t[left] = t[right];
left++;
}
while(t[left] < temp && left < right)
{
left++;
}
if(left != right)
{
t[right] = t[left];
right--;
}
}
t[left] = temp;
//对确定好位置的元素的左右子数组进行排序
quickSort2(t, begin, left - 1);
quickSort2(t, left + 1, end);
}
template <typename T>
int printArray(T *const t, int len)
{
for(int i = 0; i < len; i++)
{
cout << t[i] << ';';
}
cout<<endl;
}
int main(int argc, char *argv[])
{
int c[10] = {9,4,6,1,11,4,5,3,10,0};
quickSort2(c, 0, sizeof(c)/sizeof(int) - 1);
printArray(c, sizeof(c)/sizeof(int));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ c