Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save m-primo/650bb26fcd96ab5fd5af8c0f36367a33 to your computer and use it in GitHub Desktop.
Save m-primo/650bb26fcd96ab5fd5af8c0f36367a33 to your computer and use it in GitHub Desktop.
Simple Linear, Binary, Jump & Interpolation Search Implementation in C++
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void showArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << ", ";
}
cout << endl;
}
void linearSearch(int number, int arr[], int size) {
int pos = -1;
for(int i = 0; i < size; i++) {
if(arr[i] == number) {
pos = i + 1;
}
}
return pos;
}
void binarySearch(int number, int arr[], int size) {
int pos = -1;
int beg = 0;
int mid = 0;
int end = size - 1;
int flag = 0;
while(beg <= end && number != arr[mid]) {
mid = (beg + end) / 2;
if(number == arr[mid]) {
pos = mid + 1;
flag++;
}
if(number < arr[mid]) {
end = mid - 1;
} else {
beg = mid + 1;
}
}
if(flag == 0 && number == arr[mid]) {
pos = mid + 1;
flag++;
}
if(flag == 0) {
pos = -1;
}
return pos;
}
void jumpSearch(int number, int arr[], int size) {
int pos = -1;
int step = sqrt(size);
int index = 0;
bool flag = false;
while(arr[min(step, size) - 1] < number) {
index = step;
step += sqrt(size);
if(index >= size) flag = false;
}
while(arr[index] < number) {
index++;
if(index == min(step, size)) flag = false;
}
if(arr[index] == number) {
//found
flag = true;
pos = index + 1;
}
if(!flag) {
//not found
pos = -1;
}
return pos;
}
void interpolationSearch(int number, int arr[], int size) {
int pos = -1;
int index = 0;
int beg = 0;
int end = size - 1;
bool flag = false;
while(beg <= end && number >= arr[beg] && number <= arr[end]) {
if(beg == end) {
if(arr[beg] == number) index = beg;
}
index = (beg) + ((end - beg) / (arr[end] - arr[beg])) * (number - arr[beg]);
if(arr[index] == number) {
//found
flag = true;
pos = index + 1;
}
if(arr[index] < number) beg = index + 1;
else end = index - 1;
}
if(!flag) {
//not found
pos = -1;
}
return pos;
}
int main() {
int arr[] = {45,23,35,422,51,74,755,154,1,22,10};
int size = sizeof(arr) / sizeof(int);
int number;
showArray(arr, size);
cout << endl;
cout << "Enter the number you want to search: ";
cin >> number;
int searchPos = linearSearch(number, arr, arrSize); // search function here
if(searchPos != -1) {
cout << "Number found at position: " << searchPos << endl;
} else {
cout << "Not found!" << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment