1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <vector>
#include <fstream>
#include <bitset>
using namespace std;
int binarySearch(int, vector<int>, int);
void selectionSort(int, vector<int>);
int linearSearch(int, vector<int>, int);
void store_data(int, vector<int>);
int main()
{
int n, x, y, z; vector<int> data;
cout << "Enter n (number of inputs): "; cin >> n;
cout << "Enter numbers...\n";
for(int i = 0; i < n; i++)
{
cout << "> "; cin >> x;
data.push_back(x);
}
selectionSort(n, data);
cout << "search number: "; cin >> y;
z = binarySearch(n, data, y);
if(z == -1)
cout << "value not found";
else
cout << "value found! POS: " << (z+1) << endl;
return 0;
}
int binarySearch(int n, vector<int>data_1, int value)
{
int position = -1; bool found = false;
int first = 0, middle, last = n-1;
while(first <= last && !found)
{
middle = (first+last)/2;
if(data_1[middle] == value)
{
found = true;
position = middle;
}
else if(data_1[middle] > value)
last = middle-1;
else
first = middle+1;
}
return position;
}
void selectionSort(int n, vector<int>data_1)
{
int mI, mV;
for(int i = 0; i < n-1; i++)
{
mI = i;
mV = data_1[i];
for(int j = i+1; j < n; j++)
{
if(data_1[j] < mV)
{
mV = data_1[j];
mI = j;
}
}
data_1[mI] = data_1[i];
data_1[i] = mV;
}
for(int i = 0; i < n; i++)
cout << data_1[i] << endl;
}
|