直接插入排序
直接插入排序是每次把无序序列中的第一个元素,然后插入到有序序列的合适位置,即排序过程中会出现两部分,一部分是已排序的有序序列,还有一部分是待排序的无序序列。
排序过程通过一个二重循环实现。外层循环确定下一个待排序的值,即无序序列的第一个元素,内层循环实现对待排序元素插入位置的查找。
直接插入排序C++实现:
/****************************
*Name:直接插入排序.cpp
*Tags:排序
*Note:
*****************************/
#include <iostream>
#define MAX_SIZE 1000
using namespace std;
int InsertSort(int *, int, int);
int main()
{
int array[MAX_SIZE];
int len, i;
cout << "Input the length of the array: ";
cin >> len;
for(i = 0; i < len; i++) {
cin >> array[i];
}
InsertSort(array, 0, len); //简单插入排序
cout << "The result of the Insertion Sort:" << endl;
for(i = 0; i < len; i++) {
cout << array[i] << " ";
}
cout << endl;
return 0;
}
int InsertSort(int *array, int start, int end)
{
int temp, i, j;
for(i = start+1; i < end; i++) {
temp = array[i];
j = i;
while(j > start && array[j-1] > temp) {
array[j] = array[j-1];
j--;
}
array[j] = temp;
} //排序过程
return 0;
}
直接插入排序的时间复杂度为O(n^2),直接插入排序是一个稳定的排序算法。