Use of vectors and binary search in English

Asked

Viewed 210 times

0

One of the most commonly used activities on the computer is to locate an object (number or string) in a data set. You should develop an algorithm that allows you to find a number in a vector of 100 sequential numbers from 1 to 100.

Requirements: Numbers should be generated and stored in a vector at the time of execution.

The search algorithm to be implemented is binary search.

The user must enter the number they want to check if it is in the array.

The system must criticize if the user typed number between 1 and 100.

If he has typed numbers outside this range the system must inform that it only accepts numbers from 1 to 100. Tells you how many comparisons it took to locate the number.

For that question I made the following algorithm:

principal


// Declarações

    inteiro num[100];
    inteiro valorDig, meio, fim, inicio;
    logico continuar, encontrou;
    fim = 100;
    inicio = 1;
    encontrou = falso;


    // Instruções
    escreva("Digite o desejado: ");
    leia(valorDig);
    enquanto (inicio<=fim e nao encontrou) faca
        meio = (fim + inicio)/ 2;
        se (num[meio] == valorDig) entao
            encontrou = verdadeiro;
        fimSe
        se (num[meio] > valorDig) entao
            fim = meio - 1;
        senao
            inicio = meio + 1;

        fimSe
    fimEnquanto



fimPrincipal

I did not succeed, I wanted help to know what I can fix or even if someone would have a better solution.

1 answer

1


Eae man, the search algorithm seems right but there are some things you can fix:

1: Fill vector with values from 1 to 100

2: insert one more if(if) to know if the beginning is greater or equal to the end, in this case you would have to leave the while because the search ended, you can use an interruption (break) to do this.

3: You should save the search result(whether or not you found the number searched).

Good luck there I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.