## Direct insert sort

In direct insertion sorting, a record is inserted into an already ordered table or array to get a new ordered table or array.

Just like playing cards, when you get a card, you have to put it in your hand to make it orderly. If there are 4, 6 and 7 cards in your hand, the next card you get now is 5, then you must insert it after 4, and it's the same with direct insertion and sorting.

If you now have an array: {11,2,5,78,34,56,23}, insert the sorting directly as follows:

The code implementation is as follows:

```
void InsertSort(int a[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i]; // The key to be inserted is a[i]
for (j = i - 1; a[j] > temp && j >= 0; j--) { // Find the location of a[i]
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
```

Analysis shows that when the keyword to be inserted in the figure above is 78, 78 is larger than the previous one, so there is no need for this sorting, so you can judge whether it needs to be carried out before each sorting.

The code implementation is as follows:

```
void InsertSort(int a[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
if (a[i] < a[i - 1]) { // If sorting is needed, that is to say, a[i] is smaller than its previous one, and a[i] and the previous one cannot form an ordered sequence
temp = a[i];
for (j = i - 1; a[j] > temp && j >= 0; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}
```

## Time complexity of direct insertion sorting

The best case for direct insertion sorting is that the array to be sorted is ordered, so it only needs to be compared. But if it is the worst case, that is, the array is in reverse order, then its time complexity will be relatively large, so its average time complexity is O(n2). Direct insertion sort is a sort algorithm with stable time complexity in simple sort.

A stable sort when inserting Sort directly.

## Binary Insertion Sort

We know that half search is faster than sequence search, through which we can optimize the direct insertion sort. In the past, when looking for the location of the keyword to be inserted, we used sequential search and comparison. Now we change the previous sequential search to half search.

```
void BiInsertSort(int a[], int n) {
int i, j, temp;
int low, high, mid;
for (i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
temp = a[i]; // a[i] is the keyword to be inserted
low = 0;
high = i - 1; // From 0 to I is an ordered sequence in which a[i] is inserted at a suitable position
while (low < high) {
mid = (low + high) / 2;
if (a[mid] > temp) // a[i] before mid
high = mid - 1;
else
low = mid + 1; // a[i] after mid
}
for (j = i - 1; j >= low; j--)
a[j + 1] = a[j]; // Record backward
a[low] = temp;
}
}
}
```