转载请注明出处。
假设升序排列n个元素。
1、将序列分为有序区和无序区,排序前,有序区元素个数为1,无序区个数为n-1。
2、将无序区的第一个元素插入到有序区,插入位置通过比较确定,直接插入排序是稳定的排序算法。
3、插入过程中需要向右移动插入位置后的元素。
时间复杂度:
最坏情况下,比较次数为n(n-1)/2,时间复杂度为O()。
测试代码:
#include<iostream>
#include<iterator>
using namespace std;
void insertionSort(int list[], int length){
int temp, index;
for(int firstOutOfOrder=1; firstOutOfOrder < length; firstOutOfOrder++)
if(list[firstOutOfOrder] < list[firstOutOfOrder-1])
{
temp = list[firstOutOfOrder];
list[firstOutOfOrder] = list[firstOutOfOrder-1];
index = firstOutOfOrder-1;
while(index > 0 && list[index-1] > temp)//find insertion location
{
list[index] = list[index-1];
index--;
count++;
}
list[index] = temp;
}
}
int main(){
ostream_iterator<int> screen(cout, ", ");
int list[] = {9, 8, 7, 6, 5, 4};
insertionSort(list, sizeof(list)/sizeof(int));
copy(list, list+sizeof(list)/sizeof(int), screen);
cout << endl;
}
参考资料: