Internal sort: Insert sort and hill sort of n kind implementations

Source: Internet
Author: User
Tags comparison sort

Objective

Originally want to sum up all the internal sorting for a blog, but with the in-depth research, or give up the idea, before drinking, or feel separate to write better, specific reasons, after reading this blog is naturally clear.

This article focuses on the insertion sort and hill sort, where the two are put together, obviously because Hill sorting is based on the insertion sort.

Note: The following algorithms are the most of the n implementation of the algorithm based on the idea that I wrote out, or to refer to its own classic implementation, I have tested through, but can not guarantee that there will be no problem, if there is doubt, welcome to point out.

Insert Sort

The idea of inserting a sort is simple, and its basic operation is to insert a data into a sequence that has already been sorted so as to get a new ordered sequence. Depending on the way to find the insertion position, it can be divided into: direct insertion sort, binary insertion sort, 2-way insertion sort ... Here, we mainly explore the next direct insertion sort and binary insertion sort.

Direct Insert Sort

Direct insertion ordering is the most basic method of inserting and sorting, and is also the simplest sort method. Its basic realization thought is as follows:

1, first the first element as an ordered sequence, in turn, the following elements into the ordered sequence;

2. When inserting, the element is compared with the elements in the preceding ordered sequence, and the suitable insertion position is found to form a new ordered sequence.

3. When an ordered sequence expands to the size of the entire original sequence, the sort ends.

The first method of implementation

According to the idea, the implementation code I wrote the first time was as follows:

/* The 
first form 
of code inserts the order after the small to 
large
/void insert_sort1 (int *arr,int len)  
{  
    int i;  
    Loop from 1th element to insert sort  
    for (i=1;i<len;i++)     
    {   //Compare the first element with the preceding element and insert the appropriate position  
        if (arr[i]<arr[i-1])  
        {   //always to the left to be compared until inserted into the appropriate position  
            int key = Arr[i];  
            int count = 0;  Used to record where the key moves to the left while  
            (i>0 && key<arr[i-1])  
            {  
                Arr[i] = arr[i-1]  
                in relation to the preceding element; ARR[I-1] = key;  
                i--;  
                count++;  
            }  
            Position the number to be inserted into the next element,  
            //Because the i++ is still followed, so here is no longer 1  
            i + + count;    
        }  
}

The second method of implementation

Obviously, the above code is somewhat miscellaneous, if the interview time let you write the code to insert the order, it is difficult to be written out. So, I consider to remove the while loop, directly in the back of a For loop, each comparison, encountered larger than their exchange, until encountered smaller than themselves, to exit the For loop. This code is changed to the following form:

/* The 
second code form 
is inserted into the order after the small to large
/void insert_sort2 (int *arr,int len)  
{  
    int i,j;  
    for (i=1;i<len;i++) for  
        (j=i-1;j>=0 && arr[j]>arr[j+1];j--)  
        {//  
            exchange element values  
            //due to arr[ J] is not equal to arr[j+1],  
            //So it can be safely used to arr[j]^=arr[j+1 the Exchange method  
            ];  
            ARR[J+1]^=ARR[J];  
            ARR[J]^=ARR[J+1];  
        }  

The third method of implementation

The above code uses the exchange of data, that is, each time you want to insert the element to each other than its larger element interchange position, and data exchange requires three steps assignment operation, we can avoid doing so many operations (sorting algorithm will generally try to avoid the exchange of data operations), To improve execution efficiency (although the efficiency of this implementation may not be as significant), let's go back to the first implementation method, we can save the data to be inserted by the key variable, and then move the key to the right one when comparing, and then put it in the position to insert. This can reduce the execution time of two assignment operations. This allows us to change the code to the following implementation form:

/* The 
Third code form 
inserts sorted order for small to large
/void insert_sort3 (int *arr,int len)  
{  
    int i,j;  
    for (i=1;i<len;i++)  
        if (Arr[i] < arr[i-1])  
        {   //forward-by-comparison until the place where you want to insert  
            int key = Arr[i];  
            For (j=i-1;j>=0 && arr[j]>key;j--)  
                arr[j+1] = arr[j];  
            ARR[J+1] = key;    Insert key  
        }  
}

This is also the most common form of implementation, if you want to write handwritten inserts in the interview, directly to the implementation of the code can be written.

In addition, it is obvious that for the order of length n, the average time complexity of the direct insertion sort is O (n*n), and the comparison times of the direct insertion sort are closely related to the positions of the elements in the original sequence, and the order of the sequences closer to the order, the smaller the number of times and the smaller the complexity of the time.

Binary Insert Sort

The direct insertion sort algorithm is simple and easy to implement, when the length of the order is n very small, it is a good sort method, especially when the original sequence is close to the order, the efficiency is better. If the length to be sorted is large, it is not appropriate to use a direct sort. At this point we can consider to make some improvements, we can start by reducing the number of comparisons and moves, so we can use binary insertion sort, the idea is similar to binary lookup, no longer in detail, give the implementation code directly:

 
/* Insert sort order for small to large
/void binsert_sort (int *arr,int len)  
{  
    int i;  
    Executes the insert sort for  
    (i=1;i<len;i++)     
    {     
        int low =0, starting with the 1th element;  
        int high = i-1;  
        int key = Arr[i];  
        Loop to the two points you want to insert while  
        (Low<=high)  
        {  
            int mid = (Low+high)/2;   
            if (Key<arr[mid]) high  
                = Mid-1;  
            else low
                = mid+1;  
        }  
        Low=high+1 after the end of the loop, and the low position is the key to be inserted in the position  
      
        //from the low to I of the elements followed by an  
        int J;  
        for (j=i;j>low;j--)  
            arr[j] = arr[j-1];  
        Insert key at low position  
        arr[low] = key;  
    }  
}

As you can see from the code, the additional storage space required for the binary insertion sort is equal to the direct insert sort, while the binary insertion sort reduces the number of comparisons, but the element moves less frequently. As a result, the average time complexity of binary insert sorting is still O (n*n).

Hill sort of hill sort (shell sort), also called shrinking incremental sort. As we mentioned above, the higher the order efficiency of the direct insertion sort in the case of the more orderly the original sequence, the better the ranking of Hill is taking advantage of the direct insertion sort. The basic idea of Hill sort is as follows:

It divides the sequence into several subsequence according to an increment interval, and then inserts the sequence into the subsequence, then takes another increment interval, inserts the sorted subsequence, and then ... The sequence is ordered, and then the whole sequence is inserted (i.e., the increment interval is 1), thus the ordered sequence is obtained.

The focus of this article is on the implementation of various code of the sorting algorithm, so no longer to elaborate on the specific implementation of ideas, readers can access the relevant materials or books to familiarize themselves with the specific ideas of hill sort. Since hill sorting is used for insertion sequencing, we then write the hill-sorted code according to the three different implementations of the basic insertion sort above.

The first method of implementation

A careful analysis of the idea of the hill sort implementation will find that if you want to iterate through the sequence of sequences, we need to add a for loop to the outside of the sort code to loop through all the subsequence. We write the following code based on the first implementation of the insert sort:

/* The 
first form of code 
a trip to an array of long Len for Ader insert sort the 
algorithm is modified in the first implementation form of the insertion sort algorithm to get
/void shell_insert1 (int * Arr,int len,int Ader)  
{  
    int i,k;  
    Loops Insert sort operations on Ader  
    (k=0;k<ader;k++) for  
        (I=ader+k;i<len;i+=ader)      //Insert sort operations on a subsequence  
        {   ///Compare the first element with the elements of each ader position, insert the appropriate position  
            if (Arr[i]<arr[i-ader])  
            {   //always to the left to compare, Until inserted into the appropriate position  
                int key = Arr[i];  
                int count = 0;  Used to record the key when compared to the previous element to move a few ader lengths while  
                (I>k && Key<arr[i-ader])  
                {  
                    Arr[i] = Arr[i-ader];  
                    Arr[i-ader] = key;  
                    I-= Ader;  
                    count++;  
                }  
                Position the number to be inserted into the next element, perform the next insertion sort  
                //Because the I+=ader is also followed, so go back to the original position  
                i + = Count*ader;    
            }  

The second method of implementation

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.