码迷,mamicode.com
首页 > 编程语言 > 详细

《算法导论》习题2.3-4 插入排序的递归版本

时间:2014-11-06 00:26:59      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   java   for   sp   div   log   

伪代码:

RECURSIVE-INSERT-SORT (A, n) 
  if n>1
     RECURSIVE-INSERT-SORT (A ,n-1)
     InsertLastNumber (A,n)

InsertLastNumber (A,n)
  temp = A[n]
  i=n-1
  while i>0 && A[i]>temp
    A[i+1] = A[i]
    i -=1
  A[i+1]=temp

Java实现:

public class RecursiveInsertSort {
    public static void sort(double A[] , int n)
    {
        if(n>1)
        {    
            sort(A,n-1);
            insert(A,n);
        }
        return ;
    }
    public static void insert(double A[],int n)
    {
        double temp = A[n-1];
        int i = n-2;
        while(i>=0 && A[i]>temp)
        {
            A[i+1] = A[i];
            i--;
        }
        A[i+1]=temp;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        double [] A = {1.3, 5 ,2, 6.9, 2.0,7.8,4.3};
        RecursiveInsertSort.sort(A,A.length);
        for(double a:A)
            System.out.print(a+" ");
    }

}

 

《算法导论》习题2.3-4 插入排序的递归版本

标签:style   blog   color   ar   java   for   sp   div   log   

原文地址:http://www.cnblogs.com/wzm-xu/p/4077528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!