TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
binary_insertion_sort.cpp
Go to the documentation of this file.
1
42#include <algorithm>
43#include <cassert>
44#include <iostream>
45#include <vector>
46
51namespace sorting {
52
62template <class T>
63int64_t binary_search(std::vector<T> &arr, T val, int64_t low, int64_t high) {
64 if (high <= low) {
65 return (val > arr[low]) ? (low + 1) : low;
66 }
67 int64_t mid = low + (high - low) / 2;
68 if (arr[mid] > val) {
69 return binary_search(arr, val, low, mid - 1);
70 } else if (arr[mid] < val) {
71 return binary_search(arr, val, mid + 1, high);
72 } else {
73 return mid + 1;
74 }
75}
76
83template <typename T>
84void insertionSort_binsrch(std::vector<T> &arr) {
85 int64_t n = arr.size();
86
87 for (int64_t i = 1; i < n; i++) {
88 T key = arr[i];
89 int64_t j = i - 1;
90 int64_t loc = sorting::binary_search(arr, key, 0, j);
91 while (j >= loc) {
92 arr[j + 1] = arr[j];
93 j--;
94 }
95 arr[j + 1] = key;
96 }
97}
98} // namespace sorting
99
104static void test() {
105 /* descriptions of the following test */
106 /* 1st test:
107 [5, -3, -1, -2, 7] returns [-3, -2, -1, 5, 7] */
108 std::vector<int64_t> arr1({5, -3, -1, -2, 7});
109 std::cout << "1st test... ";
111 assert(std::is_sorted(std::begin(arr1), std::end(arr1)));
112 std::cout << "passed" << std::endl;
113
114 /* 2nd test:
115 [12, 26, 15, 91, 32, 54, 41] returns [12, 15, 26, 32, 41, 54, 91] */
116 std::vector<int64_t> arr2({12, 26, 15, 91, 32, 54, 41});
117 std::cout << "2nd test... ";
119 assert(std::is_sorted(std::begin(arr2), std::end(arr2)));
120 std::cout << "passed" << std::endl;
121
122 /* 3rd test:
123 [7.1, -2.5, -4.0, -2.1, 5.7] returns [-4.0, -2.5, -2.1, 5.7, 7.1] */
124 std::vector<float> arr3({7.1, -2.5, -4.0, -2.1, 5.7});
125 std::cout << "3rd test... ";
127 assert(std::is_sorted(std::begin(arr3), std::end(arr3)));
128 std::cout << "passed" << std::endl;
129
130 /* 4th test:
131 [12.8, -3.7, -20.7, -7.1, 2.2] returns [-20.7, -7.1, -3.7, 2.2, 12.8] */
132 std::vector<float> arr4({12.8, -3.7, -20.7, -7.1, 2.2});
133 std::cout << "4th test... ";
135 assert(std::is_sorted(std::begin(arr4), std::end(arr4)));
136 std::cout << "passed" << std::endl;
137}
138
143int main() {
144 test(); // run self-test implementations
145 return 0;
146}
static void test()
Self-test implementations.
int main()
Main function.
for working with vectors
int64_t binary_search(std::vector< T > &arr, T val, int64_t low, int64_t high)
Binary search function to find the most suitable pace for an element.
void insertionSort_binsrch(std::vector< T > &arr)
Insertion sort function to sort the vector.