// 文件目录 ./PackageL/
package PackageL;
public class InsertionSort {
private static void exchangeValue(Object[] arr, Integer parm1, Integer parm2) {
Object temp = arr[parm1];
arr[parm1] = arr[parm2];
arr[parm2] = temp;
}
private static void log_i(String msg) {
System.out.println(msg);
}
public Object[] insertSort(Object[] sortarray) {
if ((sortarray.length < 1) || (sortarray.length == 1)) {
return sortarray;
}
for (Integer i = 1; i < sortarray.length; i++) {
for (Integer j = i - 1; j > -1; j--) {
if (sortarray[i] instanceof Integer) {
if ((Integer) sortarray[i] < (Integer) sortarray[j]) {
exchangeValue(sortarray, i, j);
i = i-2;
} else {
break;
}
} else if (sortarray[i] instanceof Character) {
if ((Character) sortarray[i] < (Character) sortarray[j]) {
exchangeValue(sortarray, i, j);
i = i-2;
} else {
break;
}
} else if (sortarray[i] instanceof Double) {
if ((Double) sortarray[i] < (Double) sortarray[j]) {
exchangeValue(sortarray, i, j);
i = i-2;
}else{
break;
}
} else if (sortarray[i] instanceof String) {
if ((sortarray[i].toString().compareTo(sortarray[j].toString())) > 0) {
exchangeValue(sortarray, i, j);
i = i-2;
} else {
break;
}
}
}
}
log_i("Sort Finished");
return sortarray;
}
}
使用demo和测试样例
// 文件目录 ./
import PackageL.InsertionSort;
public class InsertionSortDemo {
private static void printArray(Object[] printArray, String... arrName) {
if (arrName.length == 0) {
;
} else {
System.out.printf("%s: ", arrName[0]);
}
for (Object element : printArray) {
System.out.print(element);
System.out.print(" ,");
}
System.out.println();
}
public static void main(String[] args) {
Long startTime = System.nanoTime();
InsertionSort insertSort = new InsertionSort();
// Object[] sortArrThird = { 5, 4};
// Object[] sortArrThird = { 5, 4, 3, 2};
// Object[] sortArrThird = { 5, 4, 3, 2, 1};
// Object[] sortArrThird = {"E", "a", "c", "D"};
// Object[] sortArrThird = {"1.3", "1.2", "1.1", "1.0"};
Object[] sortArrThird = { "dcd", "esd" };
printArray(sortArrThird, "Orignal");
Object[] arraySortedThird = insertSort.insertSort(sortArrThird);
printArray(arraySortedThird, "Array Sorted: ");
System.out.printf("Run time : %fms", (System.nanoTime() - startTime)/1000000.0);
}
}
支持整形,浮点,字符,字符串排序。
End.