Array al [0, mid-1] and Al [mid, num-1] are their respective orders, the two sub-ordered segments of array al [0, num-1] merge, obtain the overall order of Al [0, num-1 ].

Source: Internet
Author: User

Problem description:

Array al [0, mid-1] and Al [mid, num-1] are their respective orders, the two sub-ordered segments of array al [0, num-1] merge, obtain the overall order of Al [0, num-1. The space complexity is O (1 ). Note: The al [I] element supports the '<' operator.


Idea: because the space complexity is required to be O (1), Merge Sorting 1 cannot be used to traverse 0 ~ Mid-1, compare it with a [Mid], if a [Mid] <A [I]; then switch it to 22, traverse a [Mid ~ cyclically ~ Length]. If a [Mid]> A [Mid + 1] After switching in 1, the system performs switching, performs insertion sorting, and inserts a [Mid] to the correct position.
Program

# Include <iostream>
Using namespace STD;
Void insertsort (int A [], int index, int length) {int temp; For (INT I = index; I <length; I ++) {if (a [I]> = A [I + 1]) {temp = A [I]; A [I] = A [I + 1]; A [I + 1] = temp ;}}}
Void sort (int A [], int mid, int length) {int temp; For (INT I = 0; I <= mid-1; I ++) {if (a [Mid] <A [I]) {temp = A [I]; A [I] = A [Mid]; A [Mid] = temp; insertsort (A, mid, length-1 );}}}
Int main () {int A [11] = {1, 4, 6, 7, 10, 2, 3, 8, 9, 15, 16}; sort (, 5, 11); For (INT I = 0; I <11; I ++) cout <A [I] <""; return 0 ;}

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.