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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int s_search(int s); // function declarations
void bubblesort();
void b_search();
void insertionsort();
int arr[] = { 3,5,4,2,7,8 }; // array values to construct vector
vector<int> v(arr, arr + sizeof(arr) / sizeof(arr[0])); // vector initialization
int main() { // main function starts here
int c = 0, value; // integers for operations
cout << "1.) To sequential search:\n";
cout << "2.) For bubblesort :\n";
cout << "3.) For binary search:\n";
cout << "4.) To add values to vector and insertionsort it\n";
cout << "5.) To exit\n";
cin >> c; // reading input number from the user
while (c != 5)
{
cout << "1.) To sequential search:\n";
cout << "2.) For bubblesort :\n";
cout << "3.) For binary_search:\n";
cout << "4.) To add values to vector and insertionsort it\n";
cout << "5.) To exit";
cin >> c;
switch (c) // switch to select users option
{
case 1: cout << "Enter a value to search:";
cin >> value;
s_search(value); break;
case 2:bubblesort(); break;
case 3: b_search(); break;
case 4: cout << "Enter an element to add:\n";
cin >> value;
v.push_back(value);
insertionsort();
break;
case 5:cout << "Thank you"; break;
ddefault: "Done"; break;
}
}
return 0;
}
int s_search(int n) // searching a value sequential search
{
for (int i = 0; i < v.size(); i++) {
if (v[i] == n)
return i;
}
return -1;
}
void bubblesort() // bubble sort function
{
bool swapp = true;
while (swapp) {
swapp = false;
for (int i = 0; i < v.size(); i++) {
if (v[i]>v[i + 1]) {
v[i] += v[i + 1];
v[i + 1] = v[i] - v[i + 1];
v[i] -= v[i + 1]; // swapping on the comparisiion
swapp = true;
}
}
}
for (int i = 0; i <v.size(); i++) {
cout << v[i] << " "; // printing after sorting
}
cout << endl;
}
bool myfunction(int i, int j) { return (i<j); } // temperaroy function to compare
void b_search() // binary search function
{
// using default comparison:
std::sort(v.begin(), v.end());
std::cout << "looking for a 3... ";
if (std::binary_search(v.begin(), v.end(), 3))
std::cout << "found!\n"; else std::cout << "not found.\n";
// using myfunction as comp:
std::sort(v.begin(), v.end(), myfunction);
std::cout << "looking for a 6... ";
if (std::binary_search(v.begin(), v.end(), 6, myfunction))
std::cout << "found!\n"; else std::cout << "not found.\n";
}
void insertionsort() // function- insertion sort
{
int i, j, tmp;
for (i = 1; i < v.size(); i++) {
j = i;
while (j > 0 && v[j - 1] > v[j]) {
tmp = v[j];
v[j] = v[j - 1];
v[j - 1] = tmp;
j--;
}
}
for (int k = 0; k<v.size(); k++)
cout << v[i];
}
|