【算法实现】插入排序算法

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

package org.bupt.test;
import java.util.ArrayList;
class MyResource {
	ArrayList<Integer> arrList= new ArrayList();
	public MyResource(ArrayList<Integer> arrList) {
		this.arrList = arrList;
	}
	public void insertionSort() {
		int j;
		
		/*将数组向右平移一位,留出arrList[0],用作哨兵*/
		arrList.add(arrList.get(arrList.size()-1));
		for (j =  arrList.size()-1; j>0;j--) {
			arrList.set(j, arrList.get(j-1));
		}
		
		for (int i = 1; i < arrList.size(); i++) {
			if (arrList.get(i)<arrList.get(i-1)) {
				arrList.set(0, arrList.get(i)) ;
			
				/*在查找循环中"监视"下标变量j是否越界。一旦越界(即j=0),因为arrList[0]和自己比较,循环判定条件不成立使得查找循环结束,
				 * 从而避免了在该循环内的每一次均要检测j是否越界(即省略了循环判定条件"j>=1")。 */
				for (j = i-1; arrList.get(0) < arrList.get(j); j--) {
					arrList.set(j+1, arrList.get(j));
				}
			
				arrList.set(j+1, arrList.get(0));
			}
		}
	}
	public void printOut() {
	    for (int i = 1; i < 10; i++) {
			System.out.print(arrList.get(i)+" ");
		}
	}
}
public class Main {
  public static void main(String args[]) throws Exception {
    ArrayList<Integer> arrList = new ArrayList(10); 
    
    for (int i = 0; i < 9; i++) {
		arrList.add(new Integer((int) (Math.random()*100)));
		System.out.print(arrList.get(i)+" ");
	}
    System.out.println("");
    
    MyResource mtMyResource = new MyResource(arrList);
    
    mtMyResource.insertionSort();
    
    mtMyResource.printOut();
    
  }
}

 

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

posted @ 2013-01-04 11:12  gnuhpc  阅读(294)  评论(0编辑  收藏  举报