Simple Insertion Sort 插入排序
/**
* 將位置p上的元素向左移動,直到它在前p+1個元素中的正確位置被找到的地方
* @param a an array of Comparable items
*/
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(AnyType[] a) {
int j;
for (int p = 1; p < a.length; p++) {
AnyType tmp = a[p];
for (j = p; j > 0 && tmp.compareTo(a[j-1]) < 0; j--) {
a[j] = a[j-1];
}
a[j] = tmp;
}
System.out.println(Arrays.toString(a));
}
Shell Sort 希爾排序
/**
* @param a an array of Comparable items
*/
public static <AnyType extends Comparable<? super AnyType>> void shellSort(AnyType[] a) {
int j;
for (int gap = a.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < a.length; i++) {
AnyType tmp = a[i];
for (j = i; j >= gap && tmp.compareTo(a[j - gap]) < 0; j -= gap) {
a[j] = a[j - gap];
}
a[j] = tmp;
}
}
System.out.println(Arrays.toString(a));
}
Binary Sort 二分排序
/**
* @param a an array of Comparable items
*/
public static <AnyType extends Comparable<? super AnyType>> void binarySort(AnyType[] a) {
Integer i,j;
Integer low,high,mid;
AnyType temp;
for(i=1;i<a.length;i++){
temp=a[i];
low=0;
high=i-1;
while(low<=high){
mid=(low+high)/2;
if(temp.compareTo(a[mid]) < 0) {
high=mid-1;
} else {
low=mid+1;
}
}
for(j=i-1;j>high;j--)
a[j+1]=a[j];
a[high+1]=temp;
}
System.out.println(Arrays.toString(a));
}
Bubble Sort 冒泡排序
/**
* @param a an array of Comparable items
*/
public static <AnyType extends Comparable<? super AnyType>> void bubbleSort(AnyType[] a) {
Integer i,j;
AnyType temp;
for(i=1;i<a.length;i++) {
for(j=0;j<a.length-i;j++) { //循環找到下沉"氣泡",每下沉一位,下次比較長度較小一位
if(a[j].compareTo(a[j+1]) > 0) {
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp; //將"氣泡"下沉到當前比較的最後一位
}
}
}
System.out.println(Arrays.toString(a));
}
Selection Sort 選擇排序
/**
* @param a an array of Comparable items
*/
public static <AnyType extends Comparable<? super AnyType>> void selectSort(AnyType[] a) {
Integer i,j,min;
AnyType temp;
for(i=0;i<a.length-1;i++) {
temp=a[i];
min=i; //將當前位置元素看成最小值元素(實際上是要將最小值元素交換到當前)
for(j=i+1;j<a.length;j++) {
if(temp.compareTo(a[j]) > 0) { //用a[i]和後面全部元素逐個比較,找到最小指的下標並記錄
temp=a[j]; //下一位小於前一位,則將下一位賦值給temp並繼續往右移動比較
min=j; //最小值的下標,賦值給min
}
}
a[min] = a[i]; //將最小值元素的和當前元素交換,使得當前元素爲其後面全部元素中最小值
a[i] = temp;
}
System.out.println(Arrays.toString(a));
}