Answer to Question #344795 in C++ for king

Question #344795

Write a complete C++ program that • Creates a 12 element integer array containing elements between 0 and 20 using the rand function. • After creating the array, sort it using any of the sorting methods then ask the user to guess a number between 0 and 20. • To search if the number is in the array, create a menu: 1: Linear 2: Binary. The different search algorithms are to be created in separate Functions. • int LinearSearch(int list[], int size, int value) • int BinarySearch(int list[], int size, int value) • if it is guessed number is found the chosen function should return the index of the value to the main function, then the main function should sshow index and value to the user


1
Expert's answer
2022-05-25T10:22:38-0400
#include <iostream>
#include <cstdlib>     // srand
#include <time.h>    
using namespace std;


void bubbleSort(int arr[], int n)
{
    int temp;
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - i - 1; j++)
            if (arr[j] > arr[j + 1]){
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1]=temp;
            }
}


int random(int min, int max){


    return rand()%(max-min)+min;
}
int LinearSearch(int list[], int size, int value){
    for(int i = 0; i<size; i++){
        if(list[i]==value)
            return i;
        if(list[i]>value)   return -1;
    }
    return -1;    
}
int BinarySearch(int list[], int size, int value){
    int low = 0, high = size, mid;
    while(true){
        mid = (low+high)/2;
        if(list[mid]==value)
            return mid;
        else if(list[mid]>value)
            high = mid;
        else if(list[mid]<value)
            low = mid;
        if(low+1>=high)
            return -1;
    }
}
int main()
{
    srand((unsigned) time(0));
    int n = 12;
    int guessNum, searchChoice, index;
    int array[n];
        for(int i = 0; i<n; i++){
            array[i] = random(0, 20);
        }
        
    bubbleSort(array, n);


    cout<<"Guess a number between 0 and 20: ";
    cin>> guessNum;


    cout<<"1: Linear"<<endl<< "2: Binary "<<endl;
    cin>>searchChoice;
    
    if(searchChoice==1)
        index = LinearSearch(array, n, guessNum);
    else if(searchChoice==2)
        index = BinarySearch(array, n, guessNum);
    if(index == -1)
        cout<<"Value: "<<guessNum<<" Index: None"<<endl;
    else
        cout<<"Value: "<<guessNum<<" Index: "<<index<<endl;
        
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS