1. Insert sort-Direct Insert sort (Straight insertion sort)
Basic idea:
Inserts a record into a sorted ordered table to get a new ordered table with a record number of 1. That is, the 1th record of the sequence is first considered as an ordered subsequence, and then inserted from the 2nd record, until the entire sequence is ordered.
IMPORTANT: Set up sentinels for temporary storage and judgment of array boundaries.
If you encounter an element that is equal to the insertion element, the insertion element places the elements that you want to insert behind the equality element. Therefore, the order of the equal elements is unchanged, the order from the original unordered sequence is the order after the sequence, so the insertion sort is stable.
#include <iostream>
#include <string>
using namespace std;
void print (int a[],int n,int i) {
cout << i << ":";
for (int j=0;j < 8; j + +) {
cout << a[j] << "";
}
}
void Insertsort (int a[],int n) {for
(int i=1;i<n;i++) {
if (A[i]<a[i-1]) {
int j=i-1;
int x=a[i];//copied as Sentinels, that is, storing the
a[i]=a[i-1];//of a while
(X < a[j]) {
a[j+1]=a[j];
j--;
}
A[j+1]=x
}
}} int main () {
int a[8]={3,1,5,7,4,2,9,6};
Insertsort (a,8);
Print (a,8,8);
}