資料結構學習(C++)之排序

來源:互聯網
上載者:User

測試程式

後面的常式,都是對數組的排序,使用靜態鏈表的也適用於鏈表的排序。為簡單起見,只對單關鍵碼排序,並且最後的結果都是從頭到尾按升序排列。下面是統一的測試程式:

#include <iostream>
#include <iomanip>
using namespace std;
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include "InsertSort.h"
#define random(num) (rand() % (num))
#define randomize() srand((unsigned)time(NULL))
#define N 10000 //排序元素的數目
#define SORT InsertSort //排序方法
class timer//單位ms
{
public:
void start() { start_t = clock(); }
clock_t time() { return (clock() - start_t); }
private:
clock_t start_t;
};
int KCN, RMN; timer TIMER;
void test(int a[])
{
TIMER.start();
SORT<int>(a, N, KCN, RMN);
cout << "\tTimeSpared: " << TIMER.time() << "ms" << endl;
cout << "KCN=" << left << setw(11) << KCN;
cout << "KCN/N=" << left << setw(11)<< (double)KCN/N;
cout << "KCN/N^2=" << left << setw(11)<< (double)KCN/N/N;
cout << "KCN/NlogN=" << left << setw(11)<< (double)KCN/N/log((double)N)*log(2.0) << endl;
cout << "RMN=" << left << setw(11) << RMN;
cout << "RMN/N=" << left << setw(11)<< (double)RMN/N;
cout << "RMN/N^2=" << left << setw(11)<< (double)RMN/N/N;
cout << "RMN/NlogN=" << left << setw(11)<< (double)RMN/N/log((double)N)*log(2.0) << endl;
}
int main()
{
int i;
//randomize();為了在相同情況下比較各個排序演算法,不加這句
int* ascending = new int[N];//升序序列
int* descending = new int[N];//降序序列
int* randomness = new int[N];//隨機序列
for (i = 0; i < N; i++) { ascending[i] = i; randomness[i] = i; descending[i] = N - i - 1;}
for (i = 0; i < N; i++) swap(randomness[i], randomness[random(N)]);
cout << "Sort ascending N=" << N; test(ascending);
cout << "Sort randomness N=" << N; test(randomness);
cout << "Sort descending N=" << N; test(descending);
return 0;
}

需要說明一點,KCN(關鍵碼比較次數)、RMN(記錄移動次數)並不是演算法必須的,是為了對演算法的效能有個直觀的評價(不用那些公式算來算去)。對10000個整數排序應該是最省事的測試手段,建議不要再增多記錄數目了,一是在最壞的情況不用等太久的時間,二是避免KCN、RMN溢出,另外有些遞迴的演算法在情況比較糟的時候,記錄數目太多堆棧可能會溢出,導致程式崩潰。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.