序:一个爱上Java最初的想法一直没有磨灭:”分享我的学习成果,不管后期技术有多深,打好基础很重要“。
工具类Swapper,后期算法会使用这个工具类:
复制代码 代码如下:
package com.meritit.sortord.util;
public class Swapper {
private Swapper() {
}
public static
int anotherIndex, T[] array) {
if (array == null) {
throw new NullPointerException("null value input");
}
checkIndexs(oneIndex, anotherIndex, array.length);
T temp = array[oneIndex];
array[oneIndex] = array[anotherIndex];
array[anotherIndex] = temp;
}
public static void swap(int oneIndex, int anotherIndex, int[] array) {
if (array == null) {
throw new NullPointerException("null value input");
}
checkIndexs(oneIndex, anotherIndex, array.length);
int temp = array[oneIndex];
array[oneIndex] = array[anotherIndex];
array[anotherIndex] = temp;
}
private static void checkIndexs(int oneIndex, int anotherIndex,
int arrayLength) {
if (oneIndex < 0 || anotherIndex < 0 || oneIndex >= arrayLength
|| anotherIndex >= arrayLength) {
throw new IllegalArgumentException(
"illegalArguments for tow indexs [" + oneIndex + ","
+ oneIndex + "]");
}
}
}
直接插入排序,InsertionSortord:
复制代码 代码如下:
package com.meritit.sortord.insertion;
public class InsertionSortord {
private static final InsertionSortord INSTANCE = new InsertionSortord();
private InsertionSortord() {
}
public static InsertionSortord getInstance() {
return INSTANCE;
}
public void doSort(int... array) {
if (array != null && array.length > 0) {
int length = array.length;
// the circulation begin at 1,the value of index 0 is reference
for (int i = 1; i < length; i++) {
if (array[i] < array[i - 1]) {
// if value at index i is lower than the value at index i-1
int vacancy = i; // record the vacancy as i
// set a sentry as the value at index i
int sentry = array[i];
// key circulation ,from index i-1 ,
for (int j = i - 1; j >= 0; j--) {
if (array[j] > sentry) {
array[j + 1] = array[j];
vacancy = j;
}
}
// set the sentry to the new vacancy
array[vacancy] = sentry;
}
}
}
}
public
if (array != null && array.length > 0) {
int length = array.length;
for (int i = 1; i < length; i++) {
if (array[i].compareTo(array[i - 1]) < 0) {
T sentry = array[i];
int vacancy = i;
for (int j = i - 1; j >= 0; j--) {
if (array[j].compareTo(sentry) > 0) {
array[j + 1] = array[j];
vacancy = j;
}
}
array[vacancy] = sentry;
}
}
}
}
}
测试TestInsertionSortord:
复制代码 代码如下:
package com.meritit.sortord.insertion;
import java.util.Arrays;
public class TestInsertionSortord {
public static void main(String[] args) {
InsertionSortord insertSort = InsertionSortord.getInstance();
int[] array = { 3, 5, 4, 2, 6 };
System.out.println(Arrays.toString(array));
insertSort.doSort(array);
System.out.println(Arrays.toString(array));
System.out.println("---------------");
Integer[] array1 = { 3, 5, 4, 2, 6 };
System.out.println(Arrays.toString(array1));
insertSort.doSortT(array1);
System.out.println(Arrays.toString(array1));
}
}



