代码是这样的:
void Sort(int TargetArr[], int StartPos, int EndPos) {
EndPos--;//防止调用出数组外
if (StartPos + 50 >= EndPos) {//如果数组大小小于等于50(较小)
for (int i = StartPos + 1; i <= EndPos; i++) {//使用插入排序排完剩下的50个元素
int Key = TargetArr[i];
int j = i - 1;
while (j >= StartPos && TargetArr[j] > Key) {
TargetArr[j + 1] = TargetArr[j];
j--;
}
TargetArr[j + 1] = Key;
}
return;
}
int MidNumPos = StartPos + (EndPos - StartPos) / 2;//三数取中
if (TargetArr[StartPos] > TargetArr[MidNumPos]) {
int SwapTemp = TargetArr[StartPos];
TargetArr[StartPos] = TargetArr[MidNumPos];
TargetArr[MidNumPos] = SwapTemp;
}
if (TargetArr[MidNumPos] > TargetArr[EndPos]) {
int SwapTemp = TargetArr[MidNumPos];
TargetArr[MidNumPos] = TargetArr[EndPos];
TargetArr[EndPos] = SwapTemp;
if (TargetArr[StartPos] > TargetArr[MidNumPos]) {
int SwapTemp = TargetArr[StartPos];
TargetArr[StartPos] = TargetArr[MidNumPos];
TargetArr[MidNumPos] = SwapTemp;
}
}
int Pivot = TargetArr[MidNumPos];//设置基准数
int LessPivot = StartPos;//小于基准的边界
int GreaterPivot = EndPos;//大于基准的边界
int i = StartPos;//当前元素的索引
while (i <= GreaterPivot) {
if (TargetArr[i] < Pivot) {//将当前元素交换到小于基准的部分
int SwapTemp = TargetArr[i];
TargetArr[i] = TargetArr[LessPivot];
TargetArr[LessPivot] = SwapTemp;
LessPivot++;
i++;
} else if (TargetArr[i] > Pivot) {//将当前元素交换到大于基准的部分
int SwapTemp = TargetArr[i];
TargetArr[i] = TargetArr[GreaterPivot];
TargetArr[GreaterPivot] = SwapTemp;
GreaterPivot--;
} else {
i++;
}
}
EndPos++;//这个时候已经不怕溢出了,因为希尔排序计算过程中已经-1了,所以再给他加回来
//对较小的数组执行希尔排序,对较大的数组执行递归计算,既减少了快速排序的递归次数,又减少了希尔排序的调用次数,使得速度提高
if (((LessPivot - 1) - StartPos) < (EndPos - (GreaterPivot + 1))) {
//希尔排序start=StartPos, end=(LessPivot - 2)
int n = (LessPivot - 2) - StartPos + 1;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = StartPos + gap; i <= (LessPivot - 2); i++) {
int Temp = TargetArr[i];
int j;
for (j = i; j >= StartPos + gap && TargetArr[j - gap] > Temp; j -= gap) {
TargetArr[j] = TargetArr[j - gap];
}
TargetArr[j] = Temp;
}
}
//递归较大数组
Sort(TargetArr, GreaterPivot + 1, EndPos);
} else if (((LessPivot - 1) - StartPos) > (EndPos - (GreaterPivot + 1))) {
//希尔排序start=(GreaterPivot + 1), end=(EndPos - 1)
int n = (EndPos - 1) - (GreaterPivot + 1) + 1;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = (GreaterPivot + 1) + gap; i <= (EndPos - 1); i++) {
int Temp = TargetArr[i];
int j;
for (j = i; j >= (GreaterPivot + 1) + gap && TargetArr[j - gap] > Temp; j -= gap) {
TargetArr[j] = TargetArr[j - gap];
}
TargetArr[j] = Temp;
}
}
//递归较大数组
Sort(TargetArr, StartPos, LessPivot - 1);
} else {//如果两数组大小相等,则一起递归
Sort(TargetArr, StartPos, LessPivot - 1);
Sort(TargetArr, GreaterPivot + 1, EndPos);
}
}
现在排序出的结果只能大概排出一个范围,有些地方(相邻或者接近相邻)的地方会出错,能帮忙看看是哪里的问题嘛,非常感谢!