C++ Selection sort and Binary Search help

Write a program that lets the user enter a charge account number. The program should
determine if the number is valid by checking for it in the following list:
5658845 4520125 7895122 8777541 8451277 1302850
8080152 4562555 5552012 5050552 7825877 1250255
1005231 6545231 3852085 7576651 7881200 4581002

Initialize a one-dimensional array with these values. Then use a simple linear search to
locate the number entered by the user. If the user enters a number that is in the array, the
program should display a message saying the number is valid. If the user enters a number
not in the array, the program should display a message indicating it is invalid.

Binary Search instead of linear search.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;

void SelectionSort(int List[],int n) // n for # of account
{
    for (int i = 0; i<n-1; i++) //we need to do n-2 passes
    {
        int iMin = i;
        for(int j = i+1; j<n;j++)
        {
            if( List[j] < List[iMin])
                iMin = j;
        }
        int temp = List[i];
        List[i] = List[iMin];
        List[iMin] = temp;
    }
}

int BinarySearch(const int[], int, int);
const int ACCTS = 18;
int main()
{
    
    int List[ACCTS] = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 1250255, 1005231, 6545231, 3852085, 7576651, 7881200, 4581002};
    int AcctNum,
        Result;
    cout << "Enter our charge account number to determine if it is valid: ";
    cin >> AcctNum; //enter account number
    
    Result= BinarySearch(List,ACCTS, AcctNum);
    if (Result == -1)
        cout << "Account number " << AcctNum << " is invalid.\n";
        else
            cout << "Account number " << List[Result] <<"is valid\n";
            return 0;
}
int BinarySearch(int list,int ACCTS, int AcctNum)
{
    int low = 0,
        high = ACCTS-1,
        middle,
        position= -1;
    bool found = false;
    
    while (!found && low<= high)
    {
        int middle = (low+high)/2;
        if(AcctNum == list[middle])
        {
            found = true;
            position = middle;
            
        }
        else if(AcctNum < list[middle])
            high = middle-1; //x lies before mid
        else low = middle+1; // x lies after mid
    }
    return position;
}
how do i recall the selection sort in the main function? I have a terrible professor and I dont know what im doing...
A binary search requires a sorted list.
You need to call your sorting function SelectionSort() before calling BinarySearch()

Perhaps you can try add this line
SelectionSort(List, ACCTS);
before line 31.
Last edited on
Topic archived. No new replies allowed.