基于算法I-IV,另外添加了计时的函数,QueryPerformanceCounter。
平台相关,编译环境VisualStudio 2005。
// sort_algorithm1_4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <stdlib.h>
#include <windows.h>

using namespace std;

template <class Item>

void exch(Item &A, Item &B) ...{ Item t = A; A = B; B = t; }

template <class Item>

void compexch(Item &A, Item &B) ...{ if(B < A) exch(A, B); }

// 插入法 排序
template <class Item>
void insert_sort(Item a[], int l, int r)

...{
for(int i = l + 1; i <= r; i++)
for(int j = i; j > l; j--)
compexch(a[j-1], a[j]);
}

// 冒泡法 排序
template <class Item>
void bubbleup_sort(Item a[], int l, int r)

...{
for(int i = r; i >= l + 1; i--)
for (int j = 1; j <= i; j++)
compexch(a[j-1], a[j]);
}

// 选择 排序
template <class Item>
void selection_sort(Item a[], int l, int r)

...{
int MIN;

for(int i = l; i <= r; i++)...{
MIN = i;
for(int j = i + 1; j <= r; j++ ) if(a[j] < a[MIN]) MIN = j;
exch(a[i], a[MIN]);
}
}

int main(int argc, char *argv[])


...{
// Before running.
LARGE_INTEGER frequency, start, end;
int i, N = atoi(argv[1]), sw = atoi(argv[2]);
int *a = new int[N];


if(!QueryPerformanceFrequency(&frequency))...{
printf("ERROR! QueryPerformanceFrequency fails. RC: %d. ", GetLastError());
}


if(sw)...{
for(i = 0; i < N; i++)
a[i] = (int)1000*(1.0*rand()/RAND_MAX);

} else ...{
N = 0; while (cin >> a[N]) N++;
}
for (i = 0; i < N; i++) cout << a[i] << " ";
cout << endl;

if(!QueryPerformanceCounter(&start))...{
printf("ERROR! QueryPerformanceCounter fails. RC: %d. ", GetLastError());
}

selection_sort(a, 0, N-1);


if(!QueryPerformanceCounter(&end))...{
printf("ERROR! QueryPerformanceCounter fails. RC: %d. ", GetLastError());
}
cout << "Total Time: " << (end.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart << " uSeconds." << endl;
for (i = 0; i < N; i++) cout << a[i] << " ";
cout << endl;
}
选择排序算法执行示例:
sort_algorithm1_4.exe 100 1 100表示产生100个随机数,1表示使用随机数产生数据。
d:> sort_algorithm1_4.exe 100 1
1 563 193 808 585 479 350 895 822 746 174 858 710 513 303 14 91 364 147 165 988 445 119 4 8 377 531 571 601 607 166 663
450 352 57 607 783 802 519 301 875 726 955 925 539 142 462 235 862 209 779 843 996 999 611 392 266 297 840 23 375 92 677
56 8 918 275 272 587 691 837 726 484 205 743 468 457 949 744 108 599 385 735 608 572 361 151 225 425 802 517 989 751 34
5 168 657 491 63 699 504
Total Time: 27 uSeconds.
1 4 8 8 14 23 56 57 63 91 92 108 119 142 147 151 165 166 168 174 193 205 209 225 235 266 272 275 297 301 303 345 350 352
361 364 375 377 385 392 425 445 450 457 462 468 479 484 491 504 513 517 519 531 539 563 571 572 585 587 599 601 607 607
608 611 657 663 677 691 699 710 726 726 735 743 744 746 751 779 783 802 802 808 822 837 840 843 858 862 875 895 918 925
949 955 988 989 996 999