Advertisement
andresouzaabreu

sorting algorithm

Apr 7th, 2020
606
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. /**
  8.  * Finds the vector index of the searched value OR the index of the greatest value less than the searched value.
  9.  *
  10.  * @param vector $haystack An ordered array of integers
  11.  * @param int $needle The element to be found
  12.  * @return int $index The index of the matching element.
  13. */
  14. int vector_search(vector<int> haystack, int needle) {
  15.     int start = 0, end = haystack.size() - 1, middle = ceil((start + end) / 2);
  16.  
  17.     while (end - start > 1) {
  18.         if (haystack[middle] == needle) {
  19.             return middle;
  20.         }
  21.  
  22.         if (haystack[middle] > needle) {
  23.             end = middle;
  24.         } else {
  25.             start = middle;
  26.         }
  27.  
  28.         middle = ceil((start + end) / 2);
  29.     }
  30.  
  31.     if (haystack[end] == needle) {
  32.         return end;
  33.     }
  34.  
  35.     return start;
  36. }
  37.  
  38. int main() {
  39.     int N;
  40.     vector<int> numbers;
  41.     numbers.reserve(N);
  42.    
  43.     for (int i = 0; i < N; i++) {
  44.         int value, position;
  45.         cin >> value;
  46.         position = vector_search(numbers, value);
  47.         numbers.insert(position + 1, value);
  48.     }
  49.  
  50.     for (int i = 0; i < (N - 1); i++) {
  51.         cout << numbers[i] << " ";
  52.     }
  53.  
  54.     cout << numbers[N - 1] << endl;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement