排序数组(编辑)时的奇怪算法性能
Strange algorithm performance when sorting an array (edited)
嗨,我正在测试几个排序算法在排序大小在2500到25000之间的数组时的性能。我比较的两种排序是侏儒排序和快速排序,从我读到的这些快速排序应该快得多,但侏儒排序在任何情况下都比它快。
快速排序的代码是:
void myQuickSort(Record sRecord[], int firstElement, int lastElement, bool (*funPoint) (int,int))
{
int i = firstElement;
int j = lastElement;
int temp;
char tmpname[NAMESIZE];
int pivot = sRecord[(firstElement + lastElement) / 2].score;
bool (*myPoint)(int,int) = funPoint;
while (i <= j)
{
while (sRecord[i].score < pivot)
{
i++;
}
while (sRecord[j].score > pivot)
{
j--;
}
if(compareResult(sRecord[j].score,sRecord[i].score) == false)
{
temp = sRecord[i].score;
strcpy(tmpname,sRecord[i].name);
sRecord[i].score = sRecord[j].score;
strcpy(sRecord[i].name,sRecord[j].name);
sRecord[j].score = temp;
strcpy(sRecord[j].name, tmpname);
i++;
j--;
}
if(firstElement < j)
{
myQuickSort(sRecord, firstElement, j, compareResult);
}
if(i < lastElement)
{
myQuickSort(sRecord, i, lastElement , compareResult);
}
}
}
和GnomeSort如下:
void myGnomeSort(Record sRecord[], int size, bool (*funPoint)(int,int))
{
int pos = size, temp;
char tmpname[NAMESIZE];
bool (*myPoint)(int,int) = funPoint;
while(pos > 0)
{
if (pos == size || myPoint(sRecord[pos].score, sRecord[pos-1].score) == false)
pos--;
else
{
temp = sRecord[pos].score;
strcpy(tmpname,sRecord[pos].name);
sRecord[pos].score = sRecord[pos-1].score;
strcpy(sRecord[pos].name,sRecord[pos-1].name);
sRecord[pos-1].score = temp;
strcpy(sRecord[pos-1].name, tmpname);
pos--;
}
}
}
有谁能解释一下为什么使用快速排序(2.5k的元素和几乎5倍长的元素)会有如此急剧的增长?
Thanks for help
编辑:用于测试的代码是Record smallRecord[25000];
populateArray(smallRecord, 25000);
int startTime = GetTickCount();
for(int times = 0; times < NUMOFTIMES; times++)
{
populateArray(smallRecord, 25000);
myGnomeSort(smallRecord, 25000, compareResult);
cout << times << endl;
}
int endTime = GetTickCount();
float timeMS = ((float) (endTime - startTime)) / 1000;
cout << "Time taken: " << timeMS << endl;
填充数组函数只是用随机数填充数组
实际上快速排序的复杂度为O(N^2),平均为O(N * logN),而不是在最坏情况下。所以不鼓励使用快速排序因为总是存在这样的数据O(N^2)
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么这个运算符<重载函数对 STL 算法不可见?
- OpenMP阵列性能较差
- 递归列出所有目录中的C++与Python与Ruby的性能
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 了解算法的性能差异(如果以不同的编程语言实现)
- 为什么"quick sorting"算法的这两种变体在性能上差异如此之大?
- Dijkstra 最短路径算法性能 std::p riority_queue VS std::set.
- 提高DPLL算法的性能
- 为什么对于许多 SIMD 算法,只有 AVX 的处理器的性能优于 AVX2 处理器
- 为什么这种令人尴尬的并行算法的性能没有随着多线程而提高
- 哪种算法的性能最好
- 排序数组(编辑)时的奇怪算法性能
- 在虚拟机上运行openMp算法造成的性能损失
- Dijkstra算法实现的性能
- 解释两种几乎相同的算法的性能差异