Insert sort----Binary Insert sort algorithm __ algorithm

Source: Internet
Author: User

1, when a new element is inserted into a sorted array, the first element of the area to be inserted (the sorted range) is set to A[low] and the end element is set to A[high when the insertion point is searched, and the element and a[m are inserted when the comparison is made.
2, where m= (Low+high)/2 compared, if smaller than the reference element, then select A[low] to a[m-1] for the new insertion area (that is, high=m-1),
3, otherwise select a[m+1] to A[high] for the new insertion area (that is, low=m+1),
4, so until Low<=high is not established, after this position, all elements are moved back one bit, and the new element is inserted into a[high+1].

Binary insert sorting algorithm is a stable sorting algorithm, which significantly reduces the number of keywords compared to the direct insertion algorithm, so the speed is faster than the direct insertion algorithm, but the number of records moved does not change, so the time complexity of binary insertion sort algorithm is still O (n^2), Same as the direct insert sort algorithm. additional space O (1).
Binary lookup only reduces the number of comparisons, but the element moves the same number of times, so the time complexity of O (n^2) is correct.

 #include <iostream> using namespace std;  Binary insert sort on the record array r, length of the array is void binsort (int *r,int length) {for (int i = 2;i <= length;i++) {int x
        = R[i];

        int low = 1;

        int high = i-1;
            Determine the insertion position while (low <= high) {int mid = (low + high)/2;
            if (x < R[mid]) high = mid-1;
        else Low = mid + 1;
        The//record is moved backward for (int j = i-1;j >= low;j--) {r[j + 1] = R[j]; 
    }//Insert record R[low] = x;
    int main () {int a[] = {0,48,62,35,77,55,14,18};

    Binsort (a,7); 
for (int i = 1;i <= 7;i++) cout << a[i] << ""; }

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.