package com.example.operator;
public class InsertionSort { private InsertionSort(){}
//arr[0...i)已排序;arr[i...n)未排序
public static <E extends Comparable<E>> void sort(E[] arr){
for(int i=0;i<arr.length;i++){
//插入位置索引
E temp = arr[i];
int j;
for(j=i;j>0;j--){
if(temp.compareTo(arr[j-1])<0){
arr[j] = arr[j-1];
}
else{
break;
}
}
arr[j] = temp;
}
}
//arr[0...i)未排序;arr[i...n)已排序
public static <E extends Comparable<E>> void reverseSort(E[] arr){
for(int i=arr.length-1;i>0;i--){
//插入位置索引
E temp = arr[i];
int j;
for(j=i;j<(arr.length-1);j++){
if(temp.compareTo(arr[j+1])>0){
arr[j] = arr[j+1];
}
else{
break;
}
}
arr[j] = temp;
}
}
}
|