1. Direct Insert Sort
"Introduction to Algorithms"P10, "Data structure"P265
Insert A[j] into an already sequenced array A[1..j-1] and perform a loop traversal. The basic operation for inserting a sort is to find and insert in an ordered table. each pass the insert sort is compared back and forth to facilitate the backward movement of elements in the array .
Space complexity:O (1)(when swap is used, the site can be implemented)
Time complexity:(n^2)/4 O (n^2)
2. Expand
1 ) binary Find sort
The basic operation for inserting a sort is to find and insert in an ordered table. From the query so can think of "binary lookup" that is binary find, through binary find the insertion position, and then manipulate the array insert
Code:
Insert sort public class Insert_sort {//Direct insert sort public void Insertsort (int[] data) {if (data! Null) && (Data.length > 0) {for (int i = 1;i < data.length; i + +) {int key = data[i];//Record the number currently required to be inserted, as Sentinel int index = i-1;//Record Sentry final position to insert//always loop to find the first A position smaller than key while ((Index > 0) && (Data[index] > key)) {//Data[index + 1] = Data[index];index--;} Insert Sentry into Data[index + 1] = key;}}} Direct Insert Sort implementation method two public void InsertSort2 (int[] data) {if (data! = NULL) && (data.length > 0)) {for (int i = 1;i < dat A.length; i + +) {int key = data[i];//Record the number currently required to be inserted, as Sentinel int index = i-1;//Record Sentry final position to insert//always loop to find the first position smaller than key while (Index > 0) &&A MP; (Data[index] > key) {//Exchange data directly, the value to be inserted is inserted into the appropriate value swap (data, index + 1, index) via continuous forward switching; index--;}}} Binary insert sort public void Binaryinsertsort (int[] data) {if ((data! = NULL) && (data.length > 0)) {for (int i = 1;i < dat A.length; i + +) {int key = data[i];//Record the number currently required to be inserted as Sentinel int start = 0;int end = i-1;//binary Find while (Start < end) {int mid = (start + en d)/2;iF (Data[mid] > key)//insertion point in the first half paragraph {end = Mid-1;} else if (Data[mid] < key)//insertion point in the second half of the paragraph {start = mid + 1;} else//equal to find insertion point {start = end = Mid;}} Move the array insert, note to move forward from backward, and at this time start=midfor (int j = i-1; j > End; j--) {data[j + 1] = data[j];} Data[end + 1] = key;}}} private void Swap (int[] data, int a, int b) {int temp = Data[a];d ata[a] = data[b];d ata[b] = temp;} public static void Main (string[] args) {int data[] = {2,34,45,2,13,24,5,24,57};insert_sort Insert_sort = new Insert_sort () ; Insert_sort.binaryinsertsort (data); Main.print_array (data);}}
Sorting algorithm insertion sort (Java)