Дан отсортированный массив из 15 целых чисел. Найти позицию занимаемую элементом со значением 20. Операции с элементами массива осуществлять при помощи нотации индексов — C++(Си)

#include <iostream>
#include <conio.h>
 
using namespace std;
 
const int n = 15, need = 20;
 
int main()
{
    int ar[n];
    for(int i = 0; i < n; i++)
        cin >> ar[i];
    int res = 0;
 
    for(int len = 20; len >= 0; len--)
    {
        int temp = res | (1 << len);
        if(temp < n && ar[temp] <= need)
            res = temp;
    }
    if(ar[res] != need)
        cout << "No such number";
    else
        cout << res;
    getch();
}

Следующий вариант

#include <iostream>
using namespace std;
const int n=15;
int binsearch(int a[], int nkey);
void sort (int []);
int main()
{
    int a[n], i, k=0;
    cout<<"enter "<<n<<" elements: ";
    for (i=0; i<n; i++)
        cin>>a[i];
    sort (a);
    cout<<"Otsortirovannij: ";
    for (i=0; i<n; i++)
        cout<<a[i]<<" ";
    k=binsearch (a,20);
    if (k==-1)
        cout<<"no this number\n";
    else 
        cout<<"position: "<<k<<endl;
 
    return 0;
}
void sort (int mas[])
{
    int i, j, buf;
    for (i=0; i<n; i++)
        for (j=n-1; j>i; j--)
            if (mas[j-1]>mas[j])
            {
                buf=mas[j]; 
                mas[j]=mas[j-1];
                mas[j-1]=buf;
            }
}
int binsearch(int mas[], int nkey)
{
    int i = 0, k = n - 1;
    while(i <= k)
    {
        int j = (i + k) / 2;
        if (mas[j] == nkey)
            return j;   /* элемент найден */
        if (mas[j] < nkey)
            i = j + 1;
        else
            k = j - 1;
    }
        return -1;  /* элемента нет */
}

Leave a Comment