Created
October 26, 2022 22:48
-
-
Save giovannamoeller/ea0450d26a9c30ea7d62800f2cf73a91 to your computer and use it in GitHub Desktop.
binary search vs linear search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // main.cpp | |
| // Run Folder | |
| // | |
| // Created by Giovanna Moeller on 03/10/22. | |
| // | |
| #include <iostream> | |
| #include <vector> | |
| using namespace std; | |
| void linear_search(vector<int> arr, int target) { | |
| int count = 0; | |
| for (int i = 0; i < arr.size(); i++) { | |
| count++; | |
| if (arr[i] == target) { | |
| cout << "Linear search = " << count << " steps to find target." << endl; | |
| break; | |
| } | |
| } | |
| } | |
| void binary_search(vector<int> arr, int target) { | |
| int low = 0, mid, count = 0; | |
| int high = arr.size() - 1; | |
| while (low <= high) { | |
| mid = (low + high) / 2; | |
| count++; | |
| if (arr[mid] > target) { | |
| high = mid - 1; | |
| } else if (arr[mid] < target) { | |
| low = mid + 1; | |
| } else { | |
| cout << "Binary search = " << count << " steps to find target." << endl; | |
| break; | |
| } | |
| } | |
| } | |
| int main() { | |
| vector<int> arr = {1, 5, 7, 9, 10, 14, 18, 20, 24, 35, 36, 44, 49, 50, 51}; | |
| linear_search(arr, 5); | |
| binary_search(arr, 5); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment