Direct Insert Sort C + +

Source: Internet
Author: User

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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.