• 带哨兵的插入排序实现


    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 ; } } }

      

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

  • 相关阅读:
    移动端 h5开发相关内容总结——CSS篇
    水滴导航特效
    腾讯课堂之前端开发html5css3javascriptjQueryJS年薪20万
    阿里前端笔试总结
    Web 开发的未来:React、Falcor 和 ES6
    Yii2按需加载图片怎么做?
    Yii2 灵活加载js、css
    Ubuntu上搭建SVN
    yii pageTitle与Yii::app()->name的区别
    Mysql--Database Exception (#42) 数据库错误
  • 原文地址:https://www.cnblogs.com/iamzhoug37/p/4394557.html
Copyright © 2020-2023  润新知