带哨兵的插入排序实现

import sort.Sort;

/*
 * 有哨兵的插入排序
 */
public class InsertSortWithSentry extends Sort
{

    @Override
    public void sort(Comparable[] a)
    {

        Comparable min = a[0] ;
        int minPos = 0 ;
        for(int i=1 ; i<a.length ; i++)
        {
          if(!less(a[i] , a[minPos]))
            minPos = i ;
        }
        Comparable temp = a[0] ;
        a[0] = a[minPos] ;
        a[minPos] = temp ;

		for(int i = 1 ; i < a.length ; i++)
		{
		    for(int j = i; less(a[j - 1], a[j]) ; j--)
		    {
		        exch(a, j, j - 1) ;
		    }
		}
    
    }

    public static void main(String[] args)
    {

        Sort s = new InsertSortWithSentry() ;
        Character[] ch = new Character[] {'S' , 'H' , 'E' , 'L' , 'L' , 'S' , 'O' , 'R' , 'T' , 'E' , 'X' , 'A' ,
                                          'M' , 'P' , 'L' , 'E'
                                         } ;
        s.sort(ch);
        s.show(ch);
    }

}
public abstract class Sort
{
	public  abstract void sort(Comparable[] a) ;
	
	public boolean less(Comparable v , Comparable w)
	{
		return v.compareTo(w) > 0 ; //只有大于0才是true, 否则为false; 也就是前大于后才是true
	}
	
	public void exch(Comparable[] a , int i , int j)
	{
		Comparable o = a[i] ;
		a[i] = a[j] ;
		a[j] = o ; //访问数组4次;
	}
	
	public void show(Comparable[] a)
	{
		for(int i=0 ; i<a.length ; i++)
		{
			System.out.print(a[i] + " ");
		}
		System.out.println();
	}
	
	public boolean isSorted(Comparable[] a)
	{
		for(int i=1 ; i<a.length ; i++)
		{
			if(less(a[i],a[i-1]))
				return false ;
		}
		
		return true ;
	}
}
//不需要交换的插入排序, 使每一个大的元素向后移动一位,减少了交换带来的访问数组的次数.
public class BetterInsertSort extends Sort { public static void main(String[] args) { Sort s = new BetterInsertSort() ; Character[] ch = new Character[] {'S' , 'H' , 'E' , 'L' , 'L' , 'S' , 'O' , 'R' , 'T' , 'E' , 'X' , 'A' , 'M' , 'P' , 'L' , 'E' } ; s.sort(ch); s.show(ch); } @Override public void sort(Comparable[] a) { Comparable min = a[0] ; int minPos = 0 ; for(int i = 1 ; i < a.length ; i++) { if(!less(a[i] , a[minPos])) minPos = i ; } Comparable temp = a[0] ; a[0] = a[minPos] ; a[minPos] = temp ; for(int i = 1 ; i < a.length ; i++) { int j = i ; Comparable t = a[i] ; for( ; less(a[j - 1], t) ; j--) { a[j] = a[j - 1] ; } a[j] = t ; } } }

  

  //《算法》的笔记^_^

posted @ 2015-04-05 19:19  iamzhoug37  阅读(607)  评论(0编辑  收藏  举报