前置知识
插入排序,一般也被称为直接插入排序。对于少量元素的排序,它是一个有效的算法 。插入排序是一种最简单的排序方法,它的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增1的有序表。在其实现过程使用双层循环,外层循环对除了第一个元素之外的所有元素,内层循环对当前元素前面有序表进行待插入位置查找,并进行移动 。 -----百度百科
实现代码
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
int a[10];
void insertSort(int a[], int len) {//直接插入排序
for (int i = 1; i < len; i++) {
if (a[i] < a[i - 1]) {
int temp = a[i];
int j = i - 1;
for (; j >= 0; j--) {
if (a[j] < temp) break;
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}
void binInsertSort(int a[], int len) {//拆半插入排序
for (int i = 1; i < len; i++) {
if (a[i] < a[i - 1]) {
int temp = a[i];
int l = 0, r = i - 1;
while (l<=r)
{
int mid = l + r >> 1;
if (a[mid] > temp) r = mid - 1;
else l = mid+1;
}
for (int j = i - 1; j >= l; j--) a[j + 1] = a[j];
a[r+1] = temp;
}
}
}
void shellSort(int a[], int len) {//希尔排序
int d = len / 2;
while (d>0) {
for (int i = d; i < len; i++) {
int temp = a[i];
int j = i - d;
while (j >= 0 && a[j] > temp) {
a[j + d] = a[j];
j = j - d;
}
a[j + d] = temp;
}
d /= 2;
}
}
int main() {
//排序成递增序列
for (int i = 0; i < 10; i++) cin >> a[i];
insertSort(a,end(a)-begin(a)); //直接插入排序
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
for (int i = 0; i < 10; i++) cin >> a[i];
binInsertSort(a, end(a) - begin(a)); //拆半插入排序
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
for (int i = 0; i < 10; i++) cin >> a[i];
shellSort(a, end(a) - begin(a)); //希尔排序
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
}
//样例: 5 1 4 2 6 9 3 8 7 0