Direct insertion and sorting (recursive and non-Recursive Implementation methods)

Source: Internet
Author: User

Direct insertion and sorting (recursive and non-Recursive Implementation methods)

An array has n elements. If the first n-1 elements have been sorted, insert the n-th element to the first n-1 elements so that the arrays are sorted in an orderly manner.

As for how the n-1 elements have been sorted first, we can assume that the previous N-2 elements have been sorted, insert the n-1 elements to the previous N-2 element.

And so on until only one element is left, that is, the first element. Sorting is completed.


The Code is as follows:

# Include
 
  
Using namespace std; void Insert_Sort (int * A, int n) {int I, j, a; for (I = 0; I
  
   
Write the recursive version
   

# Include
    
     
Using namespace std; // Insert n into the preceding sorted array void Insert (int * a, int n) {int I = n-1; int key = a [n]; while (I> = 0) & key0) {Insert_Sort (A, n-1); // recursion indicates that Insert (A, n) has been sorted previously );} else // the exit for recursion is n = 0 return;} void main () {int A [4] = {21,2, 34,1}; Insert_Sort (A, 3 ); for (int I = 0; I <4; I ++) {cout <
     
Time Complexity Analysis:

1. In the best case, the raw data has been sorted, so the time complexity is O (N)

2. In the worst case, the original array is sorted in reverse order, which is O (n2)

3. On average, O (n2)


The closer the element data is to order, the higher the efficiency of direct insertion.

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.