插入排序 给出一下四种方法:
直接插入排序,折半插入排序,二路插入排序,希尔插入排序
代码实现:
#include<iostream> using namespace std; #define size 21 typedef int Sqlist[size]; void SInsertSort(Sqlist &L, int n) //直接插入 { cout << "直接插入排序" << endl; for (int i = 2; i < n; ++i) { if (L[i] < L[i - 1]) //判断i与i-1位置的大小 { L[0] = L[i]; //将i位置赋值给哨兵位 int j; for (j = i - 1; L[0] < L[j]; --j) { L[j + 1] = L[j]; //循环后移 } L[j + 1] = L[0]; } } } void BInsertSort(Sqlist &L, int n) { cout << "折半插入排序" << endl; for (int i = 2; i < n; ++i) { L[0] = L[i]; int low = 1; int high = i - 1; int mid = 0; while (low <= high) { mid = (low + high) / 2; if (L[0] < L[mid]) { high = mid - 1; } else { low = mid + 1; } } for (int j = i - 1; j >= high + 1; --j) { L[j + 1] = L[j]; //循环后移 } L[high + 1] = L[0]; } } void TWInsertSort(Sqlist &L, int n) //2—路插入排序 { cout << "二路插入排序" << endl; Sqlist T; T[0] = L[0]; int first; int last; first = last = 0; for (int i = 1; i < n; ++i) { if (L[i] < T[first]) { first = (first - 1 + n) % n; T[first] = L[i]; } else if (L[i] > T[last]) { last++; T[last] = L[i]; } else { last++; T[last] = T[last - 1]; int j = last - 1; for (; L[i] < T[(j - 1 + n) % n]; j = (j - 1 + n) % n) { T[j] = T[(j - 1 + n) % n]; } T[j] = L[i]; } } for (int i = 0; i < n; ++i) { L[i] = T[first]; first = (first + 1) % n; } } void ShellInsert(Sqlist &L, int n, int dk)//希尔插入 { int t; for (int i = dk + 1; i <= n; ++i) //按增量变化 { if (L[i] < L[i - dk]) //比较大小 { t = L[i]; int j = i - dk; for (; j>0 && t<L[j]; j -= dk) { L[j + dk] = L[j]; } L[j + dk] = t; //赋值 } } } void ShellSort(Sqlist &L, int n, int dlta[], int t)//希尔排序 { for (int k = 0; k < t; ++k) //按照增量数组值重复插入排序 { ShellInsert(L, n, dlta[k]); } } void main() { Sqlist sq = { 0, 49, 38, 65, 97, 76, 13, 27, 49 };//0为哨兵位 cout << "原数组为:" << endl; for (int i = 1; i < 9; ++i) { cout << sq[i]<<' '; } cout << endl; SInsertSort(sq,9); for (int i = 1; i < 9; ++i) { cout << sq[i] << ' '; } cout << endl; BInsertSort(sq, 9); for (int i = 1; i < 9; ++i) { cout << sq[i] << ' '; } cout << endl; Sqlist Sq = { 49, 38, 65, 97, 76, 13, 27, 49 }; cout << "原数组为:" << endl; for (int i = 0; i < 8; ++i) { cout << Sq[i]<<' '; } cout << endl; TWInsertSort(Sq, 8); for (int i = 0; i < 8; ++i) { cout << Sq[i] << ' '; } cout << endl; Sqlist sQ = { 0, 49, 38, 65, 97, 76, 13, 27, 49 };//哨兵位 cout << "原数组为:"<<endl; for (int i = 1; i <= 8; ++i) //打印sQ { cout << sQ[i] << " "; } cout << endl; int dlta[] = { 5, 3, 1 }; //增量数组 ShellSort(sQ, 8, dlta, sizeof(dlta) / sizeof(int));//希尔排序 cout << "希尔排序:" << endl; for (int j = 1; j <= 8; ++j) { cout << sQ[j] << " "; } cout << endl; }
原文地址:http://blog.csdn.net/irean_lau/article/details/46532629