diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index c8e6e6e4..695e4ef2 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -48,6 +48,7 @@ 9. [heap Sort](Sorting/heap-sort.cpp) 10. [Radix Sort](Sorting/radix-sort.cpp) 11. [Shell Sort](Sorting/shell-sort.cpp) +12. [Binary Insertion Sort](Sorting/binary-insertion-sort.cpp) ## Strings 1. [Rabin-Karp pattern search algo](Strings/rabin-karp.cpp) diff --git a/algorithms/CPlusPlus/Sorting/binary-insertion-sort.cpp b/algorithms/CPlusPlus/Sorting/binary-insertion-sort.cpp new file mode 100644 index 00000000..466eec31 --- /dev/null +++ b/algorithms/CPlusPlus/Sorting/binary-insertion-sort.cpp @@ -0,0 +1,77 @@ +#include +#include + +/** + * In normal insertion sort there will be "i" comparisons + * for every i'th iteration. + * Minimum comparison : 1 + * Maximum comparison : O(i) for every i'th iteration + * + * In binary insertion sort there will be only log(i) comparisons + * for every i'th iteration + * Minimum comparison: 1 + * Maximum comparison: O(log(i)) for every i'th iteration + * + * Still the total time complexity of the algorithm remains the same + * because of the swap in each iteration + * + * Time Complexity of binary insertion sort: O(n^2) + */ + +int binary_search(std::vector& arr, int item, int left, int right){ + /** + * Binary Search Algorithm + * + * @params: `arr` array with the elements + * @params: `size` size of the array + * + * Time complexity: O(log(n)) + */ + int mid = 0; + while(left <= right){ + mid = left + (right - left) / 2; + if(arr[mid] == item) { return mid + 1; } + if(arr[mid] < item ) { left = mid + 1; } + else { right = mid - 1; } + } + if(item > arr[left]) { return left + 1; } + else { return left; } +} + +void insertion_sort(std::vector& arr, int size){ + /* + * Insertion Sort Algorithm + * + * @params: `arr` array with the elements + * @params: `size` size of the array + * + * Time complexity: O(n^2) + */ + + for(int i=1; i= loc){ + arr[index] = arr[index-1]; + index--; + } + arr[index] = item; + } +} + +int main(){ + // I/O operation + //----------------------------------------------- + int N; + std::cout << "Enter total number of elements: "; + std::cin >> N; + std::vector arr(N); + + std::cout << "Enter the elements: " << std::endl; + for(auto& i: arr){ std::cin >> i; } + //------------------------------------------------- + + insertion_sort(arr, N); + for(const auto& i: arr){ std::cout << i << " "; } +}