标签:
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] = a[0] ; 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); Sort ss = new ShellSort() ; Character[] chch = new Character[] {‘S‘ , ‘H‘ , ‘E‘ , ‘L‘ , ‘L‘ , ‘S‘ , ‘O‘ , ‘R‘ , ‘T‘ , ‘E‘ , ‘X‘ , ‘A‘ , ‘M‘ , ‘P‘ , ‘L‘ , ‘E‘ } ; s.sort(chch); s.show(chch); } }
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 ; } }
//《算法》的笔记^_^
标签:
原文地址:http://www.cnblogs.com/iamzhoug37/p/4394557.html