Skip to content

Instantly share code, notes, and snippets.

@DreamVB
Created June 10, 2021 20:14
Show Gist options
  • Select an option

  • Save DreamVB/c87f83caa496cd4341586d2c4106bddc to your computer and use it in GitHub Desktop.

Select an option

Save DreamVB/c87f83caa496cd4341586d2c4106bddc to your computer and use it in GitHub Desktop.
Binary Search array
//Binary Search Demo
// by Ben a.k.a DreamVB
// follow me https://github.com/DreamVB
#include <iostream>
using namespace std;
//Bubble sort
template <typename T>
void bubble_sort(T *arr, size_t size){
T t;
for (size_t x = 0; x < size; x++){
for (size_t y = x + 1; y < size; y++){
//Compare the data and swap
if (arr[x] > arr[y]){
//Temp data
t = arr[y];
//Do the swap
arr[y] = arr[x];
arr[x] = t;
}
}
}
}
//Display the contents of an array
template <typename T>
void print_array(T *arr, size_t size){
int x = 0;
while (x < size){
std::cout << arr[x] << " ";
x++;
}
}
//Binary search in an array and return the position the item was found.
template <typename T>
int Binary_Search(T *arr, size_t left, size_t right, T data){
if (right >= left){
size_t mid = left + (right - left) / 2;
//check the middle of the array
if (arr[mid] == data){
return mid;
}
//Check left side
if (arr[mid] > data){
return Binary_Search(arr, left, (mid - 1), data);
}
else{
//Check right side.
return Binary_Search(arr, (mid + 1), right, data);
}
}
//Return not found
return -1;
}
template <typename T>
void show_result(int index, T find){
if (index == -1){
std::cout << find << " was not found in the array" << std::endl;
}
else{
std::cout << find << " was found in the array at position: " << index << std::endl;
}
}
int main(){
size_t size = 10;
int idx =-1;
int z = 0;
int nums[10] = { 9, 2, 4, 7, 6, 3, 1, 0, 5, 8 };
char *alpha;
alpha = new char[26];
//Sort the array first as binary search requires sorted data
bubble_sort(nums, size);
//Show data in the nums array
print_array(nums, size);
//line break
std::cout << std::endl;
//Locate the number 6 in the sorted array using binary serach
idx = Binary_Search(nums, 0, size - 1, 6);
//Show find staus
show_result(idx, 6);
//line break
std::cout << std::endl;
//Fill alpha array with letters A-Z
//Note we don't use the sort on this as it's in order
for (char letter = 'A'; letter <= 'Z'; letter++){
alpha[z] = letter;
z++;
}
//Show array
print_array(alpha, 26);
//Find Q in the alpha array
idx = Binary_Search(alpha, 0, 25, 'Q');
//line break
std::cout << std::endl;
//Show find staus
show_result(idx, 'Q');
//line break
std::cout << std::endl;
//Clear up
delete[]alpha;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment