1、插入排序
思想:将无需组中的第一个数插入到有序数组中,这样经过N-1次插入即可完成排序。
C++实现
#include <IOSTREAM> using namespace std; void Insert_Sort(int a[],int n); int main(void) { int a[] = {1,3,5,5,3,2,4}; for (int i=0;i<sizeof(a)/sizeof(a[0]);i++) { cout << a[i] << endl; } Insert_Sort(a,sizeof(a)/sizeof(a[0])); cout << "afert sort:" << endl; for (i=0;i<sizeof(a)/sizeof(a[0]);i++) { cout << a[i] << endl; } return 0; } void Insert_Sort(int a[],int n) { for(int i=1;i<n;i++) { int temp = a[i]; for (int j=i;j>0;j--) { if(temp>a[j-1]) { a[j] = temp; break; } else { a[j] = a[j-1]; } } } }
void Insert_Sort(int *a, int n) { int key = 0; int i, j,k; for (k = 0; k < n; k++) { cout << a[k] << ""; } cout << endl; for (j = 1; j < n; j++) { key = a[j]; i = j - 1; while (i >= 0 && key < a[i]) { a[i + 1] = a[i]; i--; } a[i + 1] = key; for (k = 0; k < n; k++) { cout << a[k] << ""; } cout << endl; } }
时间复杂度最坏O(N^2),平均O(N^2),扫描次数N-1.如果是有序数列,则复杂度为O(N-1)。稳定性:稳定