排序算法及實現(2)

直接插入排序

直接插入排序(straight insertion sort)的基本思想是:每次將一個待排序的記錄,按其大小插入到前面已經排好序的子表中的適當位置,直到全部記錄插入完成爲止。

JAVA實現

/**
 * @(#)InsertSort.java
 *
 * InsertSort application
 *
 * @author kuroro
 * @version 1.00 2011/9/3
 */
public class InsertSort
{
   public static int[] Sort(int[] num)     
   //直接插入排序   
   { 
   	   for(int i=1;i<num.length;i++)     
   	   {  int temp=num[i];         
           int j=0;   
               for(j=i-1;j>=0&&temp<num[j];j--)
              
                {            
        	       num[j+1]=num[j];
                }
              num[j+1]=temp;   
              } 
          
          return num;   
       }
}


測試實例

class TestInsert {
	public static void main(String[] args)
	{
		int[] array = {9,8,7,6,5,4};
		InsertSort.Sort(array);
		for(int i=0;i<array.length;i++)
		System.out.print(array[i]+" ");
	}
}

 

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章