/**
* Copyright (C) 2015, CSU
* All rights reserved
* File Name:test.cpp
* Author: lmm
* Date of completion: 2015/1/19
* Version: v1.0
*
* 问题描述:直接插入排序
* 输入描述: 输入整数
* 知识点 : 内部排序
* 程序输出: 输出有序整数
*/
#include <iostream>
#include <stdio.h>
using namespace std;
void InsertSort(int *seqList,int length)
{
// seqList[0]设置为监视哨,避免数组下标出界,并且存放的是当前比较中的小者
int i, j;
for (i = 2 ; i < 11; ++i) // 比较的趟数
{
if (seqList[i] < seqList[i-1]) // 当前数与前一个数比较
{
seqList[0] = seqList[i]; // 存放较小的数
seqList[i] = seqList[i-1]; // 两者比较后将较大的数往后移动一个位置,较小的数之前已被存放在哨兵位置seqList[0]
for (j = i-2; seqList[0] < seqList[j]; --j) // 由于当前数已与前一个比较,所以现在比较哨兵与i-2之前的数
{
seqList[j+1] = seqList[j]; // 哨兵与前几个数依次比较,较大数后移,每趟比较后i之前所有的数都已排序好
}
seqList[j+1] = seqList[0]; // 将哨兵存放在合适位置
}
}
}
int main()
{
int a[11] = {0};
int result[10] = {0};
int seqNum = 0;
cout << "Input ten numbers: ";
for (int i = 1; i < 11; ++i) // 输入10个数,result[0]为哨兵
{
cin >> seqNum;
a[i] = seqNum;
}
InsertSort(a,11); // 直接插入排序
cout << endl << "Output the results: ";
for (int j = 0, i = 1; j < 10 && i < 11; ++i,++j)
{
result[j] = a[i];
cout << result[j] << " ";
}
cout << endl;
return 0;
}
当待排序列中记录按关键字非递减有序排列时,所需进行关键字比较的次数达最小值n-1(即 ),记录不需移动
当待排序列中记录按关键字非递增有序排列时,总的比较次数达最大值(n+2)(n-1)/2 (即),记录移动的次数也达最大值(n+4)(n-1)/2(即
)
若待排序列中的记录是随机的,即可能出现的各种排列的概率是相同的,则可取上述最大值和最小值的平均值,作为直接插入排序时所需进行关键字间的比较次数和移动记录的次数,约为 由此,直接插入排序的时间复杂度为
。