双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

关于一个排序算法的问题

adventurelw adventurelw 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
实在是头大了。。。
关于快速排序的算法,个人觉得应该是对的,但就是对一个数组不行。。。。。。可能当局者迷,请求大家指点一下:
#include <iostream>

const int Size = 12;
const int size = 3;
int Midnum(int a, int b, int c);//选出三个数中中间那个
void SortQui(int a[], int begin, int end);//快速排序
int main()
{
using namespace std;
int ival[Size] = {18, 4, 20, 3, 65, 37, 45, 99, 32, 12, 2, 23};
cout << "Before sorted:\n";
for(size_t i = 0; i < Size; ++i)
cout << ival[i] << " ";
cout << endl << "After sorted:\n";
SortQui(ival, 0, Size);
for(size_t i = 0; i < Size; ++i)
cout << ival[i] << " ";
cout << "Done!" << endl;
return 0;
}

int Midnum(int a, int b, int c)
{
int temp[size] = {a, b, c};
int tempval;
for(size_t i = size - 1; i > 0; --i)
for(size_t j = 0; j < i; ++j)
{
if(temp[j] > temp[j + 1])
{
tempval = temp[j];
temp[j] = temp[j + 1];
temp[j + 1] = tempval;
}
}
return temp[2];
}


void SortQui(int a[], int begin, int end)
{
int low = begin, high = end - 1;
if(low < high)
{
int Keynum = Midnum(a[low], a[high], a[(low + high) / 2]);
if(Keynum == a[high])
{
a[high] = a[low];
a[low] = Keynum;
}
else if(Keynum == a[(low + high) / 2])
{
a[(low + high) / 2] = a[low];
a[low] = Keynum;
}
while(low < high)
{
while(low < high && a[high] >= Keynum)
--high;
a[low++] = a[high];
while(low < high && a[low] <= Keynum)
++low;
a[high--] = a[low];
}
a[low] = Keynum;
SortQui(a, begin, low);
SortQui(a, low + 1, end);
}
}

main中的那个数组测试没有问题,随便再写一个数组也行,比如:8, 4, 10, 3, 15, 23, 45, 99, 32, 12, 2, 17

但这个数组不行:int a[12] = {10, 18, 9, 2, 6, 13, 20, 15, 22, 14, 8, 4};
用这个算法排出来是:2 4 6 8 9 10 15 13 14 18 20 22
15那个位置的元素一定会在排到13前边,不管大小(和13比较),比如改成100,那么
结果就是:2 4 6 8 9 10 100 13 14 18 20 22
简直要晕倒了。。。。但我实在找不到哪里出问题了。。。。。。
...全文

相关推荐

评论 14
收藏 已收藏
分享
返回顶部
adventurelw
C++ 语言 65,214 成员 250,514 内容