63.6k views
4 votes
How to write a c program asking the user for 20 numbers in descending or ascending order, which then prompts the user to enter a number to search the array by using a binary search and print whether the number is found or not.

Please use a function for a bubble sort, a read, a print and a binaty search.​

User Amresh
by
3.3k points

1 Answer

3 votes

#include <bits/stdc++.h>

#define ERR -1

std::vector<int> s;

int inp;

int eval(std::vector<int> v, int fl, int fr, int idx) {

if (fr>=fl) {

int idy = fl+(fr-fl)/2;

if (v.at(idy)==idx) return idy;

if (v.at(idy)>idx) return eval(v,fl,idy-1,idx);

return eval(v,idy+1,fr,idx);

}

return ERR;

}

std::string print_result(int input) {

int result = eval(s,0,s.size()-1,input);

return result!=ERR ? "The element found at " + std::to_string(result) + ". index!\\" : "The element not found!\\";

}

void read() {

std::cout << "Enter 20 numbers whether ascending or descending order.\\";

for(int i=0;i<20;i++) {

std::cout << "\\>>";

int fill; std::cin>>fill;

s.push_back(fill);

}

std::cout << "Which element do you want to find?: ";

std::cin>>inp;

}

int main(int argc, char* argv[]) {

read();

std::cout << print_result(inp);

return 0;

}

User Szpic
by
3.2k points