代码如下:
- Java code
package com.order.algorithm;
public class SortUtil {
public final static int INSERT = 1;
public final static int BUBBLE = 2;
public final static int SELECTION = 3;
public final static int SHELL = 4;
public final static int QUICK = 5;
public final static int IMPROVED_QUICK = 6;
public final static int MERGE = 7;
public final static int IMPROVED_MERGE = 8;
public final static int HEAP = 9;
public static void sort(int[] data) {
sort(data, IMPROVED_QUICK);
}
private static String[] name={
"insert","bubble","selection","shell","quick","merge","heap"
};
private static Sort[] impl=new Sort[]{
new InsertSort(),
new BubbleSort(),
new SelectionSort(),
new ShellSort(),
new QuickSort(),
new MergeSort(),
new HeapSort()
};
public static String toString(int algorithm){
return name[algorithm-1];
}
public static void sort(int[] data, int algorithm) {
impl[algorithm-1].sort(data);
}
public static interface Sort {
public void sort(int[] data);
}
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
- Java code
package com.order.algorithm;public class BubbleSort implements SortUtil.Sort{ public void sort(int[] data) { int temp; for(int i=0;i<data.length;i++){ for(int j=data.length-1;j>i;j--){ if(data[j]<data[j-1]){ SortUtil.swap(data,j,j-1); } } } } }
- Java code
package com.order.algorithm;public class HeapSort implements SortUtil.Sort{ public void sort(int[] data) { MaxHeap h=new MaxHeap(); h.init(data); for(int i=0;i<data.length;i++) h.remove();=new TextFie
- Java code
package com.order.algorithm;public class InsertSort implements SortUtil.Sort{ public void sort(int[] data) { int temp; for(int i=1;i<data.length;i++){ for(int j=i;(j>0)&&(data[j]<data[j-1]);j--){ SortUtil.swap(data,j,j-1); } } } }
- Java code
package com.order.algorithm;public class MergeSort implements SortUtil.Sort{ public void sort(int[] data) { int[] temp=new int[data.length]; mergeSort(data,temp,0,data.length-1); } private void mergeSort(int[] data,int[] temp,int l,int r){ int mid=(l+r)/2; if(l==r) return ; mergeSort(data,temp,l,mid); mergeSort(data,temp,mid+1,r); for(int i=l;i<=r;i++){ temp=data; } int i1=l; int i2=mid+1; for(int cur=l;cur<=r;cur++){ if(i1==mid+1) data[cur]=temp[i2++]; else if(i2>r) data[cur]=temp[i1++]; else if(temp[i1]<temp[i2]) data[cur]=temp[i1++]; else data[cur]=temp[i2++]; } } }