table of Contents
Sequentially directly from the insertion sort to find
Whether or specific implementation code from the abstract process, the directly inserted sequential search to find the basic constituent elements. Why do you say that:
- To sort through all the elements
- One element taken from "unsorted" series of numbers, into the "sorted" series of numbers. Need to "sorted" into a number of columns traversing i, so arr [i-1] <arr [i] <arr [i + 1].
It requires two basic traversal. The following discussion process algorithm
Direct insertion sort process
First, there must be a basic model in mind:
[Ordered sequence {} {} {current remaining elements to be sorted elements to be sorted}}
Ordering process:
the entire sorting process is n-1 times is inserted, i.e., a first sequence of recording as an ordered sequence, and starting from the first two records, one by one insert, until the entire sequence of ordered
Note:
When an ordered sequence into traversing not start with an index 0, but the elements to be sorted left element.
Performance sorted directly into
- Space Complexity: S(n)=O(1)
- Time Complexity: T(n)=O(\({n^2}\))
- A stable sorting method
The number of objects is set n, then the next n-1 times the worst case: Comparative Run i-i th, i th mobile
maximum number of comparisons: \ (\ {n-FRAC (n-1)} {2} \)
Maximum mobile times: \ (\ {n-FRAC (-n-1)} {2} \)
in the best case: only one time per trip comparator, comparing the total number of times without moving times n-1.
code
code 1(C++ Iterative)
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) //从下标为1的位置开始遍历
{
key = arr[i]; //保存待排序元素的值
j = i - 1; //从待排序元素的前一个开始
//找寻插入位置
while (j >= 0 && arr[j] > key) //循环条件1.不越界2.比key大
{
arr[j + 1] = arr[j];
--j;
}
arr[j + 1] = key; //移动key到待插入位置
}
}
code 2(C++ Recursive)
If you are familiar with the direct insertion sort, recursive technique, not difficult to find the following relationship:
\1. Base Case: If array size is 1 or smaller, return.
\2. Recursively sort first n-1 elements.
\3. Insert last element at its correct position in sorted array.
void insertionSortRecursive(int arr[], int n)
{
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive( arr, n-1 );
// Insert last element at its correct position
// in sorted array.
int last = arr[n-1];
int j = n-2;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > last)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = last;
}