voidinsertion_sort(intarray[],intfirst,intlast) { inti,j; inttemp; for(i=first+1;i<last;i++) { temp=array[i]; j=i-1; //与已排序的数逐一比较,大于temp时,该数移后 while((j>=0)&&(array[j]>temp)) { array[j+1]=array[j]; j--; } //存在大于temp的数 if(j!=i-1) {
array[j+1]=temp;} }
} } 这个更好: voidinsert_sort(int*array,unsignedintn) { inti,j; inttemp; for(i=1;i<n;i++) { temp=*(array+i); for(j=i;j>0&&*(array+j-1)>temp;j--) { *(array+j)=*(array+j-1); } *(array+j)=temp; } }
c++版本
#include<iterator> template<typenamebiIter> voidinsertion_sort(biIterbegin,biIterend) { typedeftypenamestd::iterator_traits<biIter>::value_typevalue_type; biIterbond=begin; std::advance(bond,1); for(;bond!=end;std::advance(bond,1))
{ value_typekey=*bond; biIterins=bond; biIterpre=ins; std::advance(pre,-1); while(ins!=begin&&*pre>key)
{ *ins=*pre; std::advance(ins,-1); std::advance(pre,-1); } *ins=key; } }
functioninsertSort($arr){ for($i=1;$i<count($arr);$i++){ $tmp=$arr[$i]; $key=$i-1; while($key>=0&&$tmp<$arr[$key]){ $arr[$key+1]=$arr[$key]; $key--; } if(($key+1)!=$i) $arr[$key+1]=$tmp; } return$arr; }
/** *插入排序 *@paramarr *@return */ private static int[] insertSort(int[]arr){ if(arr == null || arr.length < 2){ return arr; } for(inti=1;i<arr.length;i++){ for(intj=i;j>0;j--){ if(arr[j]<arr[j-1]){ //TODO: int temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; }else{ //接下来是无用功 break; } } } return arr; }
运行软件:eclipse
classProgram { staticvoidMain(string[]args) { InsertionSort(); } ///<summary> ///插入排序法 ///</summary> privatestaticvoidInsertionSort() { Console.WriteLine("插入排序法"); inttemp=0; int[]arr={23,44,66,76,98,11,3,9,7}; Console.WriteLine("排序前的数组:"); foreach(intiteminarr) { Console.Write(item+","); } Console.WriteLine(); varlength=arr.Length; for(inti=1;i<length;i++) { for(intj=i;j>0;j--) { if(arr[j]>arr[j-1]) { temp=arr[j]; arr[j]=arr[j-1]; arr[j-1]=temp; } } //每次排序后数组 PrintResult(arr); } Console.ReadKey(); } ///<summary> ///打印结果 ///</summary> ///<paramname="arr"></param> privatestaticvoidPrintResult(IEnumerable<int>arr) { foreach(intiteminarr) { Console.Write(item+","); } Console.WriteLine(); } }
procedure insertsort(var R:filetype); //对R[1..N]按递增序进行插入排序,R[0]是监视哨 begin for I := 2 To n do //依次插入R[2],...,R[n] begin R[0]:=R[I];j:=l-1; while R[0] < R[J] Do //查找R[I]的插入位置 begin R[j+1]:=R[j]; //将大于R[I]的元素后移 j:=j-1; end; R[j+1]:=R[0] ; //插入R[I] end; end; //InsertSort (运行软件:Free Pascal IDE 2.6.4)
def insertion_sort(array) array.each_with_index do |element, index| next if index == 0 #第一个元素默认已排序 j = index - 1 while j >= 0 && array[j] > element array[j + 1] = array[j] j -= 1 end array[j + 1] = element end array end
definsertSort(ilist:Array[Int])
{ for(i<-1untililist.length)
{ for(j<-(0untili).reverse)
{ if(ilist(j+1)<ilist(j))
{ valtmp=ilist(j+1) ilist(j+1)=ilist(j) ilist(j)=tmp } } } }
原文:http://www.cnblogs.com/rinack/p/5015631.html