源代码
#include <iostream>
using namespace std;
template <typename T, int N>
void InsertSort(T (&a)[N]) {
for (int i = 1; i < N; i++) {
if (a[i] < a[i - 1]) {
int j;
T tmp = a[i];
for (j = 0; a[j] < a[i]; j++)
;
for (int k = i; k >= j; k--) {
if (k != 0)
a[k] = a[k - 1];
}
a[j] = tmp;
}
}
}
template <typename T>
void InsertSort(T a[], int begin, int end) {
for (int i = begin + 1; i <= end; i++) {
if (a[i] < a[i - 1]) {
int j;
T tmp = a[i];
for (j = begin; a[j] < a[i]; j++)
;
for (int k = i; k >= j; k--) {
if (k != 0)
a[k] = a[k - 1];
}
a[j] = tmp;
}
}
}
template <typename T, int N>
void ShellSort(T (&a)[N]) {
for (int gap = N / 2; gap >= 1; gap /= 2) {
int i;
for (i = 0; i < N; i++) {
for (int j = i; j + gap < N; j += gap)
InsertSort(a, j, j + gap);
}
}
}
template <typename T, int N>
void QuickSort(T (&a)[N], int l, int h) {
if (l >= h)
return;
int low = l, high = h;
T pivot = a[l];
while (low < high) {
while (low < high && a[high] >= pivot)
high--;
a[low] = a[high];
while (low < high && a[low] <= pivot)
low++;
a[high] = a[low];
}
a[low] = pivot;
QuickSort(a, l, low - 1);
QuickSort(a, low + 1, h);
}
template <typename T, int N>
void QuickSort(T (&a)[N]) {
QuickSort(a, 0, N - 1);
}
template <typename T>
void DivideSort(T a[], int begin, int end) {
if (begin < end) {
T temp[end - begin + 1];
int mid = (begin + end) / 2;
DivideSort(a, begin, mid);
DivideSort(a, mid + 1, end);
for (int i = begin, j = mid + 1, k = 0;; i <= mid || j <= end;) {
if (i <= mid && j > end)
temp[k++] = a[i++];
if (i > mid && j <= end)
temp[k++] = a[j++];
else {
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
}
for (int i = begin, j = 0; i <= end;)
a[i++] = temp[j++];
}
}
template <typename T, int N>
void DivideSort(T (&a)[N]) {
DivideSort(a, 0, N - 1);
}
int main() {
int a[] = {25, 12, 28, 16, 33, 42, 5, 10, 57};
int b[] = {25, 12, 28, 16, 33, 42, 5, 10, 57};
int c[] = {25, 12, 28, 16, 33, 42, 5, 10, 57};
int d[] = {25, 12, 28, 16, 33, 42, 5, 10, 57};
cout<<"Origin: 25 12 28 16 33 42 5 10 57"<<endl;
InsertSort(a);
cout << "Insert sort: ";
for (int i : a)
cout << i << ' ';
cout << endl;
ShellSort(b);
cout << "Shell sort: ";
for (int i : b)
cout << i << ' ';
cout << endl;
QuickSort(c);
cout << "Qucik sort: ";
for (int i : c)
cout << i << ' ';
cout << endl;
DivideSort(d);
cout << "Divide sort: ";
for (int i : d)
cout << i << ' ';
cout << endl;
return 0;
}
运行结果
Origin: 25 12 28 16 33 42 5 10 57
Insert sort: 5 10 12 16 25 28 33 42 57
Shell sort: 5 10 12 16 25 28 33 42 57
Quick sort: 5 10 12 16 25 28 33 42 57
Divide sort: 5 10 12 16 25 28 33 42 57