排序数组(编辑)时的奇怪算法性能

Strange algorithm performance when sorting an array (edited)

本文关键字:算法 性能 数组 编辑 排序      更新时间:2023-10-16

嗨,我正在测试几个排序算法在排序大小在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)