java底功不強,看了書 ,查了網上的資料自己才寫了個插入排序。
package com.yangtao.file;

public class InsertSort {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        InsertSort insertSort 
= new InsertSort();
        
int[] a = new int[]{5,2,7,1,6,9};
        
int[] b = insertSort.sort(a);
        
for(int i = 0; i < b.length; i++){
            System.out.println(b[i]);
        }
    }
    
    
/**
     * 
@param n 將要排序的數組
     * 
@return 排好序后的數組
     
*/
    
public int[] sort(int[] n){
        
//從數組下標為1的數組開始。
        for(int j = 1; j < n.length; j++){
            
//取到第J個元素的值。
            int key = n[j];
            
int i = j - 1;//用i表示排序前的一個下標
            
//如果前面還有數據 而且前面一個數大于后面一個數,我們交換位置。
            while(i >= 0 && n[i] > key){
                n[i 
+ 1= n[i];
                i
--;
            }
            n[i 
+ 1= key;
        }
        
return n;
    }

}