数据结构_插入排序

 

// 数据结构_插入排序.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>


#define array_length 100

/*算法导论中的伪代码

INSERTION-SORT(A)
1  for j = 2 to length(A)
2    do key <- A[j]
3      // Insert A[j] into the sorted sequence A[1,j-1]
4      i = j - 1;
5      while i > 0 and A[i] > key
6           do A[i+1] <- A[i]
7   i <- i - 1;
8  A[i+1] <- key

插入排序的时间复杂度: N*N
*/

int paixu_charu(int a[],int length){

 int i = 0,j = 0;

 int shaobing = 0;

 for(j = 1; j < length;j++){
 
  shaobing = a[j];

  i = j - 1;

        /*这里我们设置后面一个数为哨兵,当第i个数,也就是哨兵前面一个数大于哨兵时,哨兵跟这个数换位置,哨兵的值不变,哨兵不断的前移
  不断的比较,所以这里我们时间复杂度最换为N*N*/
  while((i >= 0)&&(a[i] > shaobing)){
  
   a[i+1] = a[i];
   i = i - 1;
   a[i+1] = shaobing;
  
  }
 
 
 }

  return 0;

}

int _tmain(int argc, _TCHAR* argv[])
{

 int a[array_length];

 int icycle = 0;

 /*随机数生成*/

 printf("cha ru paixu before:\n");

 for(icycle = 0; icycle < array_length;icycle++){
 
  a[icycle] = ( (rand() + rand()) + icycle)*(array_length/(icycle+2));

  printf("%d ",a[icycle]);

 }

 printf("\n");

 paixu_charu(a,array_length);

 printf("cha ru paixu after:\n");

 for(icycle = 0; icycle < array_length;icycle++){
 

  printf("%d ",a[icycle]);

 }

 printf("\n");

 

 /**/

 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值