First of all, the idea of inserting a sort directly :
Inserts a number into an already ordered table, and gets a new, sequential table with an additional number.
Stability and complexity:
The direct insertion sort is a stable sorting algorithm, the time complexity is the worst O (N2), the average is O (N2), and the space complexity is O (1).
Here is my C language to achieve the direct insertion sort, if there are any problems please point out, thank you.
#include <stdio.h> #include <assert.h> #include <stdlib.h> void insertsort (int array[], int size);
void InsertSort2 (int array[], int size);
void PrintArray (int *array, int size);
int main (int argc, char const *argv[]) {int size = 0;
scanf ("%d", &size);
ASSERT (Size > 0);
int *array = (int *) calloc (size, sizeof (int));
int i = 0;
for (i = 0; i < size; ++i) {scanf ("%d", &array[i]);
} insertSort2 (array, size);
PrintArray (array, size);
Free (array);
return 0;
///Sort void insertsort (int array[], int size) {assert (array!= NULL && size > 0) In order of small to large;
int insertval = 0;
int insertpos = 0;
int i = 0;
int j = 0;
for (i = 0; i < size; ++i) {insertpos = i;
Insertval = Array[i];
Find the insertion position in ARRAY[0..I] for (j = 0; J < i; ++j) {if (array[i) < Array[j]) {insertpos = J;
Break ///When the insertion position is different from where you want to insert the element itself,//array[j ... All elements in I] move backward one if (Insertpos!= i) {int k = 0;
for (k = i; k > J;--k) {array[k] = array[k-1];
} Array[insertpos] = Insertval;
}} void PrintArray (int *array, int size) {assert (array!= NULL && size > 0);
int i = 0;
for (i = 0; i < size; ++i) {printf ("%d", array[i]);
printf ("\ n"); }
The above Insertsort () function's algorithm is not concise and efficient, and here's how I see it elsewhere:
void InsertSort2 (int array[], int size)
{
assert (array!= NULL && size > 0);
int insertval = 0;
int i = 0;
int j = 0;
for (i = 1; i < size; ++i) {
insertval = array[i];
If the i-1 element is greater than the first element, insert after moving;
//Otherwise no action is required
if (Array[i-1] > Insertval) {
j = i-1;
Find the insertion position while looking for one side and move while
(J >= 0 && array[j] > Insertval) {
array[j + 1] = Array[j];
--j;
}
Array[j + 1] = Insertval}}}
The advantage of this method is that when looking for the insertion position, it moves the element after the insertion position without two cycles.
Blogs for eight other sorting algorithms:
Common 9 kinds of internal sorting (C language Implementation)