Sort n numbers by binary insertion

From , 4 Years ago, written in C++, viewed 53 times.
URL https://pastebin.vip/view/9f62b862
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. void InsertionSortDichotomy(int A[], int n)
  4. {
  5.     //二分插入排序(类似于抓牌):从后面无序数组中取第一张牌,放到前面已经拍好的顺序中
  6.     for (int i = 1; i < n; i++)
  7.     {
  8.         int get = A[i];//抓新牌
  9.         //找新牌应该放入的位置,此处采取了二分查找法
  10.         int left = 0;
  11.         int right = i - 1;
  12.         while (left <= right)
  13.         {
  14.             int mid = (left + right) / 2;
  15.             if (A[mid] > get)
  16.                 right = mid - 1;
  17.             else
  18.                 left = mid + 1;
  19.         }
  20.         //找到新拍的位置,后面的牌依次后挪
  21.         for (int j = i - 1; j >= left; j--)
  22.             A[j + 1] = A[j];
  23.         //空出来的位置把新牌放进去
  24.         A[left] = get;
  25.     }
  26. }
  27.  
  28. int main()
  29. {
  30.     int N, i;
  31.     cin>>N;//对N个数进行二分插入排序
  32.     int A[N];
  33.     for(i = 0; i < N; i++)
  34.         cin>>A[i];
  35.     InsertionSortDichotomy(A, N);
  36.     cout<<A[0];
  37.     for (i = 1; i < N; i++)
  38.         cout<<" "<<A[i];
  39.     return 0;
  40. }
  41.  

Reply to "Sort n numbers by binary insertion"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website