`
housen1987
  • 浏览: 340180 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

直接插入排序——C语言描述

阅读更多

 

#include <stdio.h>
#define MAXSIZE 30

typedef int KeyType;
typedef int otherType;
typedef struct{
	KeyType key;
	otherType other;
}RecordType;

void straightInsertSort(RecordType R[],int n){
	int i,j;
	RecordType temp;
	//第一个元素是有序的
	i = 2;
	for(i=2;i<=n;i++){
		temp = R[i];
		for(j = i - 1;temp.key < R[j].key;j--)
			R[j+1] =R[j];
		R[j+1] = temp;
	}
}

int main(){
	RecordType R[MAXSIZE];
	int n = 5;
	int i;
	for(i=1;i<=n;i++){
		R[i].key = 22 - 2 * i;
	}
	straightInsertSort(R,5);
	for(i=1;i<=n;i++){
		printf("%d   ",R[i].key);
	}
	return 0;	
}

算法解析:

核心代码段:

 

RecordType temp;
	//第一个元素是有序的
	i = 2;
	for(i=2;i<=n;i++){
		temp = R[i];
		for(j = i - 1;temp.key < R[j].key;j--)
			R[j+1] =R[j];
		R[j+1] = temp;
	}

实例描述:

待排序数列:46 58 15 45 90 18 10 62

算法核心:取得数列的第a[i]个元素当成temp,已知有序的前i-1个元素的子数列,从后向前和子序列的值进行比较,若temp的key值不小于子序列的第j个元素的key值时,此趟插入结束,把temp放在子序列的第j+1个位置上。

 

直接插入的关键在于两步:

1 和有序子序列比较,而且是从后往前,若temp的key值小,则往前走,并将比较过的元素向后挪一个位置。

2 当temp的key值不小于当前比较的元素key值时,比较结束,把temp放在子序列的第j+1个位置上(因为j--仍在起作用)。

 

直接插入排序是稳定排序,时间复杂度为O(n^2),空间复杂度为O(1)

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics