Advertisement
Okorosso

bin insert sort

May 19th, 2021
636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono>
  3. #include <vector>
  4. #include <thread>
  5.  
  6. using namespace std;
  7.  
  8. int Binary_search(int *arr, int item, int low, int high) {
  9.     int mid = (low + high) / 2;
  10.  
  11.     if (high <= low) {
  12.         if (item > arr[low])
  13.             item = low + 1;
  14.         else item = low;
  15.         return item;
  16.     }
  17.  
  18.     if (item == arr[mid])
  19.         return mid + 1;
  20.  
  21.     if (item > arr[mid])
  22.         return Binary_search(arr, item, mid + 1, high);
  23.  
  24.     return Binary_search(arr, item, low, mid - 1);
  25. }
  26.  
  27. void InsertionSort(int *arr, int size) {
  28.     int j, location, num;
  29.     for (int i = 1; i < size; i++) {
  30.         j = i - 1;
  31.         num = arr[i];
  32.         location = Binary_search(arr, num, 0, j);
  33.         while (j >= location) {
  34.             arr[j + 1] = arr[j];
  35.             j--;
  36.         }
  37.         arr[j + 1] = num;
  38.     }
  39. }
  40.  
  41.  
  42. int main() {
  43.     using std::chrono::duration_cast;
  44.     using std::chrono::milliseconds;
  45.     using std::chrono::system_clock;
  46.     int size = 10;
  47.     while (size < 1000000) {
  48.         for (int k = 0; k < 10; k++) {
  49.  
  50.             int *arr = new int[size];
  51.             for (int i = 0; i < size; i++) {
  52.                 arr[i] = rand();
  53.             }
  54.             auto start = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
  55.             InsertionSort(arr, size);
  56.             auto end = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
  57.             auto using_time = end - start;
  58.             cout << k + 1 << ") " << size << " elements sorted for " << using_time << "ms\n";
  59.         }
  60.         size *= 10;
  61.     }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement