Define a data class, mainly to define some common methods, so that you can use the same data when writing other sorting statements and insert sorting statements to compare the execution time of the algorithm.
public class DataSource {public static int SIZE = 1001;public static int[] getIntArray(){int[] dataArray = new int[SIZE];for(int i = 1; i < SIZE; i++){dataArray[i] = SIZE - i;}return dataArray;}public static void logs(String pLog){System.out.println("longs = " + pLog);}}
Defines an insert sort class, which is mainly responsible for inserting and sorting the given data, and printing the pre-sorting array, sorting time, and sorted array.
public class SortByInsert {public static void main(String args[]) {SortByInsert mSortByInsert = new SortByInsert();mSortByInsert.sortByInsert();}public void sortByInsert() {int[] dataArray = DataSource.getIntArray();printArray("Begin", dataArray);long beginTime = System.currentTimeMillis();for (int i = 2; i < dataArray.length; i++) {moveAndInsertItem(dataArray, 1, i - 1, i);}long endTime = System.currentTimeMillis();long spendTime = endTime - beginTime;printString("spend_time(int Mills) = " + spendTime);printArray("End", dataArray);}public void moveAndInsertItem(int[] pDataArray, int pBegin, int pEnd,int pAboutInsert) {for (int i = pBegin; i <= pEnd; i++) {if (pDataArray[i] > pDataArray[pAboutInsert]) {int tmp = pDataArray[i];pDataArray[i] = pDataArray[pAboutInsert];pDataArray[pAboutInsert] = tmp;}}}public void printArray(String pTag, int[] pDataArray){for(int i = 0; i < pDataArray.length; i++){DataSource.logs(pTag + " i = " + i + " value = " + pDataArray[i]);}}public void printString(String pTag){DataSource.logs(pTag);}}
The main idea is to sort (1, 2), (1, 2, 3) ---, (1, 2, 3, ---, n) in ascending order, the complexity of the algorithm is N * n (1 + 2 + 3 + --- + n). For more information, see Xie LA ~~
Javaeye address: http://junbianli.iteye.com/blog/1815573