Java Sorting Algorithm (7): semi-insertion sorting, and java semi-insertion sorting
Java Sorting Algorithm (7): semi-insertion sorting
The half insert sorting method is also called the binary insert sorting method, which is an improved version of the direct insert sorting method, and also needs to execute the I-1 insertion. The difference lies in the I-th insertion. First, find the position where the I + 1 element should be inserted. Assume that the first data is already in order.
Code Implementation
Package com. spring. test;/*** semi-insertion sorting */public class BinaryInsertSort {public static void main (String [] args) {int [] data = new int [] {5, 3, 6, 2, 1, 9, 4, 8, 7}; print (data); binaryInsertSort (data); print (data );} /*** semi-insert * @ param data */public static void binaryInsertSort (int [] data) {for (int I = 1; I <data. length; I ++) {if (data [I] <data [I-1]) {// The element value at cache I int tmp = data [I]; // record the left boundary of the search Range int low = 0; int high = I-1; while (low <= high) {// record the intermediate position int mid = (low + high) /2; // compare the data size of the intermediate position and I to narrow the search scope. if (data [mid] <tmp) {low = mid + 1 ;} else {high = mid-1 ;}/// move the data at low --- I to one position for (int j = I; j> low; j --) {data [j] = data [J-1];} data [low] = tmp; print (data );}}} /*** exchange two data * @ param I * @ param j */public static void swap (int [] data, int I, int j) {if (I = j) {return;} data [I] = data [I] + data [j]; data [j] = data [I]-data [j]; data [I] = data [I]-data [j];} /*** print and output the array * @ param data */public static void print (int [] data) {for (int I = 0; I <data. length; I ++) {System. out. print (data [I] + "\ t");} System. out. println ();}}
Running result