从头学算法之-插入排序

以前学习排序,从冒泡排序开始,依次接触了插人排序,选择排序,快速排序,合并排序,而这些排序从最简单的开始,都运用了不同的算法方法,比如brute-force,divide-and-conquer,Decrease-and-conquer。以前对插入排序的印象不深,代码也总是记不住,今天从书上看到Decrease-and-conquer,这种思想,重新理解了插入排序在这种方法下的流程。废话少说,给出原书的伪代码以便理解。

Algorithm InsertionSort(A[0...n-1])

//Sorts a given array by insertion sort

//Input:An array A[0...n-1] of n orderable elements

//Output:Array A[0...n-1] sorted in nondecreasing order

for i<-1 to n-1 do

v<-A[i]

j<-i-1

while j>=0 and A[j]>v do

A[j+1]<-A[j]

j<-j-1

A[j+1]<-v

当然我自己也写了源码,以供参考

/*insert sort*/
#include<iostream>
#include<stdlib.h>

using namespace std;

void swap(int &a,int &b)
{
	int temp;
	temp=a;
	a=b;
	b=temp;
}

void InsertSort(int a[],int n)
{
	int v=0,i=0,j=0;
	for(i=1;i<=n-1;++i)
	 {
	 	v=a[i];
	 	j=i-1;
	 while(j>=0&&a[j]>v)
	 {
	    a[j+1]=a[j];
	 	j=j-1;
	 	a[j+1]=v;
	 }
   } 
  }
 
int main()
{
	const int array_size=5;
	int a[5]={5,8,3,2,1};
	
	cout<<"The given array is:"; 
	for(int i=0;i<5;++i)
	cout<<a[i]<<' '; 
	cout<<endl;
	
	InsertSort(a,5);
	
	cout<<"The sorted array is:"; 
	for(int i=0;i<5;++i)
	cout<<a[i]<<' '; 
	cout<<endl;
	
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值