-1

As you can see, I want to find the location of an given array.

For example :

  • I have an array {5 , 2, 3, 1} (I want to decide how many guesses I want to guess)
    • Then the program will sort it {1, 2, 3, 5}
    • At last, I'll be given a chance to guess the number which I desired how many guess (example : I want 2 number guesses, they are 5 and 3. then the program will search for the number 5 and 3. The program will tell me the location in the sorted array. Then it is "3 found at 3, 5 found at 4"

However, I have my code stuck in the sorting

this is my code :

#include <iostream>
using namespace std;
int main(void)
{
    int temp, i, j, n, list[100];
    cin>>n;
    for(i=0; i<n; i++)
    {
        cin>>list[i];
    }
    for(i=0; i<n-1; i++)
        for(j=i+1; j<n; j++)
            if(list[i] > list[j])
            {
                temp = list[i];
                list[i] = list[j];
                list[j] = temp;
            }
    for(i=0; i<n; i++)
        cout<<" "<<list[i];
    cout<<endl;
    return 0;
}

And this link is the full question of my project : http://uva.onlinejudge.org/external/104/p10474.pdf

Hiura
  • 3,500
  • 2
  • 20
  • 39
Black Cat
  • 87
  • 1
  • 2
  • 8

1 Answers1

1

There is no problem in your sort function , by the way you can solve original problem in O(nlogn) , yours is O(n^2)

code:

#include <iostream>
#include <algorithm>
using namespace std;

int binary_search(int A[], int key, int imin, int imax)
{
if (imax < imin)
return -1;
else
{
  int imid = (imax + imin)/2;

  if (A[imid] > key)
    // key is in lower subset
    return binary_search(A, key, imin, imid - 1);
  else if (A[imid] < key)
    // key is in upper subset
    return binary_search(A, key, imid + 1, imax);
  else
    // key has been found
    return imid;
}
}


int main() {
// your code goes here
int n,q;
while(1){
    cin >> n>> q;
    if(n==0)
    break;
    int* a = new int[n];
    int i;
    for(i=0;i<n;i++)
    cin >> a[i];
    sort(a,a+n);
    while(q--){
        int k;
        cin >> k;
        k=binary_search(a,k,0,n-1);
        if(k==-1)
        cout << "not found" << endl;
        else
        cout << "found at :" << k+1 << endl;
    }


}
return 0;
}
pola sai ram
  • 832
  • 7
  • 23