Sorting Algorithm Summary-semi-insert sorting
Basic Ideas
Semi-insertion sorting is a simple improvement for direct insertion sorting. For direct insertion sorting, when the I-1 needs to insert the I element into the front of the 0 ~ In the sequence of I-1 elements, you always need to start from the I-1 elements, compare each element one by one until it is found. This is obviously not using the previous 0 ~ The I-1 element has been ordered, while the half insert sorting improves this.
For semi-insertion sorting, when the I-th element needs to be inserted, it will not compare each element one by one,:
(1) calculate 0 ~ The center point of the I-1 index, that is, the element at the I index is compared with the element at the (0 + i-1)/2 Index, if the element value at the I index is large, directly in (0 + i-1)/2 ~ I-1 half the range of search; otherwise in the 0 ~ (0 + i-1)/2 half range search, this is the so-called half fold;
(2) When searching within half a range, follow the (1) method to continuously perform a half-fold search, so that the search range can be reduced to 1/2, 1/4, 1/8 ..., To quickly determine the insert position;
Java implementation code
Package com. liuhao. sort; import java. util. arrays; public class BinaryInsertSort {public static void binaryInsertSort (DataWrap [] data) {int arrayLength = data. length; for (int I = 1; I 0) {low = mid + 1;} else {high = mid-1 ;}} // backward shift for (int j = I; j> low; j --) {data [j] = data [J-1];} data [low] = tmp; System. out. println (Arrays. toString (data) ;}} public static void main (String [] args) {DataWrap [] data = {new DataWrap (21, ""), new DataWrap (30, ""), new DataWrap (49, ""), new DataWrap (30, "*"), new DataWrap (16, ""), new DataWrap (9, "")}; System. out. println ("Before sorting:" + Arrays. toString (data); binaryInsertSort (data); System. out. println ("sorted:" + Arrays. toString (data ));}}
Algorithm Analysis
Semi-insert sorting reduces the number of comparisons of keywords, but the number of records moving remains unchanged. The time complexity is the same as that of direct insert sorting.