wohyperion

Интерполяционный и линейный поиск в целочисленном массиве

Dec 20th, 2016
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. /*
  2.     Вариант 6.
  3.     Найти заданный целочисленный элемент в не отсортированном массиве.
  4.     Интерполирующий поиск.
  5. */
  6.  
  7. #include <iostream>
  8. #include <cstdlib>
  9. #include <vector>
  10. #include <fstream>
  11. #include <algorithm>
  12. #include <iterator>
  13.  
  14. using namespace std;
  15.  
  16. int linearSearch( vector<int> v, int searchItem )
  17. {
  18.     cout << "Not sorted array: ";
  19.     copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  20.     cout << endl;
  21.  
  22.     for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
  23.         if (*it == searchItem)
  24.             return distance(v.begin(), it);
  25.     return -1;
  26. }
  27.  
  28. int interpolationSearch( vector<int> v, int searchItem )
  29. {
  30.     sort(v.begin(), v.end());
  31.     cout << "Sorted array: ";
  32.     copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  33.     cout << endl;
  34.  
  35.     int mid, low = 0, high = v.size() - 1;
  36.  
  37.     while (v[low] < searchItem && v[high] >> searchItem)
  38.     {
  39.         mid = low + ((searchItem - v[low]) * (high - low)) / (v[high] - v[low]);
  40.  
  41.         if (v[mid] < searchItem)
  42.             low = mid + 1;
  43.         else if (v[mid] > searchItem)
  44.             high = mid - 1;
  45.         else
  46.             return mid;
  47.     }
  48.  
  49.     if (v[low] == searchItem)
  50.         return low;
  51.     else if (v[high] == searchItem)
  52.         return high;
  53.     else
  54.         return -1;
  55. }
  56.  
  57. int main()
  58. {
  59.     ifstream fileIn("text.txt");
  60.     vector<int> v;
  61.     int temp;
  62.     while (!fileIn.eof())
  63.     {
  64.         fileIn >> temp;
  65.         v.push_back(temp);
  66.     }
  67.     fileIn.close();
  68.  
  69.     cout << "Input the element that you want to search: ";
  70.     cin >> temp;
  71.  
  72.     cout << "Position of search element ( " << temp << " ) - Linear search: " << linearSearch(v, temp) << endl << endl;
  73.     cout << "Position of search element ( " << temp << " ) - Interpolation search: " << interpolationSearch(v, temp) << endl << endl;
  74.    
  75.     system("pause");
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment