【发布时间】:2018-11-18 22:09:09
【问题描述】:
我正在尝试实现混合插入和快速排序。任务是对大向量使用快速排序,当向量变得小于某个指定值(交叉点)时,算法应该切换到插入排序。到目前为止我有这段代码,但它没有对向量进行排序,我不知道为什么。任何帮助,将不胜感激。谢谢!
#include <iostream>
#include "console.h"
#include "vector.h" // for Vector
#include <cmath>
using namespace std;
/* Partition for quicksort algorithm */
int partition(Vector<int> &vec, int start, int end){
int lh = start +1;
int rh = end;
int pivotVal = vec[start];
while (true){
while (lh<rh && vec[lh]<pivotVal) lh++;
while (rh>lh && vec[rh]>=pivotVal) rh--;
if (lh==rh) break;
swap(vec[lh], vec[rh]);
}
if (pivotVal<vec[lh]) return start;
swap(vec[start], vec[lh]);
return lh;
}
/* Regular quicksort */
void quickSort(Vector<int> &vec, int start, int end){
if(start<end){
int pivotIndex = partition(vec, start, end);
quickSort(vec, start, pivotIndex-1);
quickSort(vec, pivotIndex+1, end);
}
}
/* Insertion sort algorithm */
void insertionSort(Vector<int> &vec, int start, int end){
int size = vec.size();
for (int i=start; i<end; i++){
int j=i;
while (j>start && vec[j-1]>vec[j]){
swap(vec[j-1], vec[j]);
j--;
}
}
}
/* Hybrid quicksort & insertion sort, as soon as the part of the vector to
sort becomes less than the crossover value, the algorithm switches to
insertion sort, otherwise it
uses quicksort */
void hybridSort(Vector<int> &vec, int start, int end, int crossover){
if(start < end){
if (end-start <= crossover){
insertionSort(vec, start, end);
} else {
int pivotIndex = partition(vec, start, end);
hybridSort(vec, start, pivotIndex-1, crossover);
hybridSort(vec, pivotIndex+1, end, crossover);
}
}
}
int main() {
Vector<int> vec {9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 14, 39, 30, 83, 92, 41};
int end = vec.size()-1;
hybridSort(vec, 0, end, 4);
cout << vec.toString() <<endl;
return 0;
}
【问题讨论】:
-
如果您不知道原因,现在是在调试器中逐步执行此代码以查找错误、编写单元测试以自动公开它们或两者兼而有之的好时机。
-
看来
partition函数有问题。其余代码对我来说看起来不错。 -
感谢您的回复。问题是,常规快速排序与该分区函数配合得很好,只是混合函数有问题。
标签: c++ algorithm sorting quicksort insertion-sort