Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Вариант 6.
- Найти заданный целочисленный элемент в не отсортированном массиве.
- Интерполирующий поиск.
- */
- #include <iostream>
- #include <cstdlib>
- #include <vector>
- #include <fstream>
- #include <algorithm>
- #include <iterator>
- using namespace std;
- int linearSearch( vector<int> v, int searchItem )
- {
- cout << "Not sorted array: ";
- copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
- cout << endl;
- for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
- if (*it == searchItem)
- return distance(v.begin(), it);
- return -1;
- }
- int interpolationSearch( vector<int> v, int searchItem )
- {
- sort(v.begin(), v.end());
- cout << "Sorted array: ";
- copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
- cout << endl;
- int mid, low = 0, high = v.size() - 1;
- while (v[low] < searchItem && v[high] >> searchItem)
- {
- mid = low + ((searchItem - v[low]) * (high - low)) / (v[high] - v[low]);
- if (v[mid] < searchItem)
- low = mid + 1;
- else if (v[mid] > searchItem)
- high = mid - 1;
- else
- return mid;
- }
- if (v[low] == searchItem)
- return low;
- else if (v[high] == searchItem)
- return high;
- else
- return -1;
- }
- int main()
- {
- ifstream fileIn("text.txt");
- vector<int> v;
- int temp;
- while (!fileIn.eof())
- {
- fileIn >> temp;
- v.push_back(temp);
- }
- fileIn.close();
- cout << "Input the element that you want to search: ";
- cin >> temp;
- cout << "Position of search element ( " << temp << " ) - Linear search: " << linearSearch(v, temp) << endl << endl;
- cout << "Position of search element ( " << temp << " ) - Interpolation search: " << interpolationSearch(v, temp) << endl << endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment