fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. const int SIZE = 20;
  5. int linearSearch(int arr[], int value, int& comparisons) {
  6. for (int i = 0; i < SIZE; ++i) {
  7. comparisons++;
  8. if (arr[i] == value) {
  9. return i;
  10. }
  11. }
  12. return -1;
  13. }
  14.  
  15. int binarySearch(int arr[], int value, int& comparisons) {
  16. int low = 0, high = SIZE - 1;
  17. while (low <= high) {
  18. int mid = (low + high) / 2;
  19. comparisons++;
  20. if (arr[mid] == value) {
  21. return mid;
  22. } else if (arr[mid] < value) {
  23. low = mid + 1;
  24. } else {
  25. high = mid - 1;
  26. }
  27. }
  28. return -1;
  29. }
  30. int main() {
  31. int arr[SIZE] = {12, 23, 95, 45, 123, 67, 24, 63, 90, 101,
  32. 21, 999, 99, 42, 666, 777, 878, 989, 154, 2024};
  33. int value;
  34. cout << "Enter a value to search for: " << endl;
  35. cin >> value;
  36. int linearComparisons = 0, binaryComparisons = 0;
  37. int linearIndex = linearSearch(arr, value, linearComparisons);
  38. if (linearIndex != -1)
  39. {
  40. cout << "Linear Search: location " << linearIndex << ", comparisons: " << linearComparisons << endl;
  41. }
  42. else
  43. {
  44. cout << "Linear Search: Number not found, comparisons: " << linearComparisons << endl;
  45. }
  46. sort(arr, arr + SIZE);
  47. int binaryIndex = binarySearch(arr, value, binaryComparisons);
  48. if (binaryIndex != -1)
  49. {
  50. cout << "Binary Search: location " << binaryIndex << ", comparisons: " << binaryComparisons << endl;
  51. }
  52. else
  53. {
  54. cout << "Binary Search: Number not found, comparisons: " << binaryComparisons << endl;
  55. }
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0.01s 5264KB
stdin
2024
stdout
Enter a value to search for: 
Linear Search: location 19, comparisons: 20
Binary Search: location 19, comparisons: 5