#include<iostream>
#include<time.h>
using namespace std;
template<class T>
inline void Swap(T& a, T& b);
template<class T>
void BubbleSort(T a[], int n);
template<class T>
void InsertionSort(T a[], int n);
template<class T>
void SelectionSort(T a[], int n);
template<class T>
void Rank(T a[], int n);
int main()
{
int n,*a1,*a2,*a3,*a4;
cout<<"please input a number(1000~60000)"<<endl;
cin>>n;
a1=new int[n];
a2=new int[n];
a3=new int[n];
a4=new int[n];
double start, finish;
for (int i = 0; i < n; i++)
{ a1[i] = n -i; // initialize
a2[i]=a1[i];
a3[i]=a2[i];
a4[i]=a3[i];
}
start = clock( );
InsertionSort(a1, n);
finish = clock( );
cout << n << ‘ ‘ << (double)(finish -start) / (CLOCKS_PER_SEC)<< endl;
start = clock( );
SelectionSort(a2, n);
finish = clock( );
cout << n << ‘ ‘ << (double)(finish -start) / (CLOCKS_PER_SEC)<< endl;
start = clock( );
Rank(a3, n);
finish = clock( );
cout << n << ‘ ‘ << (double)(finish -start) / (CLOCKS_PER_SEC)<< endl;
start = clock( );
BubbleSort(a4, n);
finish = clock( );
cout << n << ‘ ‘ << (double)(finish -start) / (CLOCKS_PER_SEC)<< endl;
delete []a1;
delete []a2;
delete []a3;
delete []a4;
system("pause");
}
template<class T>
inline void Swap(T& a, T& b)
{// Swap a and b.
T temp = a;
a = b;
b = temp;
}
/*********************Bubble Sort*************************/
/*进行n- 1次遍历,每次邻位比较,是最大数冒到最后面 */
template<class T>
void BubbleSort(T a[], int n)
{// Sort a[0:n -1] using bubble sort.
for (int i = n; i > 1; i--)
for (int i = 0; i < n -1; i++)
if (a[i] > a[i+1])
Swap(a[i], a[i + 1]);
}
/**********************Insertion Sort***********************/
/*每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕*/
template<class T>
void InsertionSort(T a[], int n)
{// Sort a[0:n-1].
for (int i = 1; i < n; i++) {
// insert a[i] into a[0:i-1]
T t = a[i];
int j;
for (j = i-1; j >= 0 && t < a[j]; j--)
a[j+1] = a[j];
a[j+1] = t;
}
}
/********************Selection sort************************/
/*将最大的数选择出来,并与每次的最后一个数进行交换 */
template<class T>
void SelectionSort(T a[], int n)
{
bool sorted = false;
for (int size = n; !sorted && (size > 1); size--)
{
int pos = 0;
sorted = true;
for (int i = 1; i < size; i++)
if (a[pos] <= a[i]) pos = i;
else sorted = false; // out of order
Swap(a[pos], a[size -1]);
}
}
/*******************Rank sort*****************************/
/*先将数组中的元素按大小给它标号,并存在另外一个相应的数组里面,
然后新建个数组按照标号读取原来数组的值,之后再把排好后的值依次赋给原来数组
*/
template<class T>
void Rank(T a[], int n) {
int *r = new int[n+1];
for(int i = 0; i < n; i++)
r[i] = 0; //initialize
for(int i = 1; i < n; i++) {
for(int j = 0; j < i; j++) {
if(a[j] <= a[i])
r[i]++;
else r[j]++;
}
} //end for
T *u = new T[n+1];
for (int i = 0; i < n; i++) {
u[r[i]] = a[i];
}
for (int i = 0; i < n; i++) {
a[i] = u[i];
}
delete []u;
} //end function