插入排序的基本思想:将序列(或数组)看作两部分,前半部分已经排好序,后半部分是待排序的。将后面待排序的元素一个一个插入到排好序的序列中,最后整个序列就是有序的了。
时间复杂度:最坏情况下的时间复杂度是O(
n2
)
空间复杂度:该算法为原地工作算法,所以所需内存空间数量为常数,所以空间复杂度为O(1)。
伪代码描述:
C++实现:
/*插入排序*/
#include <iostream>
using namespace std;
template<typename ElementType>
void InsertionSort(ElementType A[], int n);
void main() {
const int length = 6;
int array[length] = { 67,12,65,21,98,36 };
InsertionSort(array, length);
for (int i = 0; i < length; i++) {
cout << array[i] << " ";
}
system("pause");
}
template<typename ElementType>
void InsertionSort(ElementType A[], int n) {
for (int j = 1; j < n; j++) {
ElementType key = A[j];
int i = j - 1;
while (i >= 0 && A[i] > key) {
A[i + 1] = A[i];
i--;
}
A[i + 1] = key;
}
}
运行结果: