c++arrayslocate

Finding location of an array - C++


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

For example :

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


Solution

  • 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;
    }