//插入排序,穩定, 時間複雜度爲O(n^2)
import java.util.Arrays;
public class InsertSortTest {
/*public static void InsertSort(int[] a){//非降序
int j;
for(int i = 1;i < a.length;i++ ){
int temp = a[i];
for(j = i; j > 0;j--)
if(temp < a[j-1])
a[j] = a[j-1];
a[j] = temp;
}
}*/
/*public static void InsertSort(int[] a){//非升序
int j;
for(int i = 1;i<a.length;i++){
int temp = a[i];
for(j = i;j>0;j--){
if(temp>a[j-1])
a[j] = a[j-1];
}
a[j] = temp;
}
}*/
//JAVA泛型
/*public static <AnyType extends Comparable<? super AnyType>>void InsertSort(AnyType a[]){
int j;
for(int i = 1;i < a.length; i++){
AnyType temp = a[i];
for(j = i;j > 0&&(temp.compareTo(a[j-1])) > 0;j--)
a[j] = a[j-1];
a[j] = temp;
}
}*/
//二分插入排序
public static void InsertSort(int a[]){
int j;
for(int i = 1;i < a.length; i++){
int temp = a[i];
int left = 0;
int right = i-1;
while(left<=right){
int mid = (left + right) / 2;
if(temp<=a[mid])
right = mid - 1;
else
left = mid + 1;
}
for(j = i-1;j >= right + 1;--j)
a[j+1] = a[j];
a[right+1] = temp;
}
}
public static void main(String[] args){
int[] a = new int[]{5,4,3,2,1,7};
InsertSort(a);
System.out.println(Arrays.toString(a));
}
}