Good Afternoon,

How would you solve a question that states: assume an array of structure is in order by studentID field of the record, where student IDs go from 101 to 500. Write the pseudocode to find the record with a specific studentID if every single student ID from 101 to 500 is used and the array has 400 elements.
So far I have this:

int binarySearch(int a[], int key)
{
int low = 0;
int high = a.length -1;
int middle;
while(low <= high)/2;
if(key == a[middle])
return middle;
else if (key < a[middle])
high = middle -1;
else
low = middle + 1;
}
return -1;
}

But is code doesn't work because it find a record with a studentID near the end.
Any help that I can get is really appreciated and any suggestions are welcome

Thanks

Dani AI

Generated

Given the constraints — student IDs 101..500 inclusive, sorted array with exactly 400 records — the simplest, fastest solution is direct indexing. As suggested, the array position for ID N is N − 101 (arr[0] → ID 101, arr[399] → ID 500). That yields O(1) lookup and avoids the complexity in the posted binary-search attempt; correctly called out the syntax error, and ’s advice to write the manual steps (find the card) is exactly the right way to derive this mapping.

function findRecordIndex(arr, studentID):
    if studentID < 101 or studentID > 500:
        return -1   // ID out of valid range
    index = studentID - 101
    return index  // use arr[index] to fetch the record

If the array might not be dense (missing IDs) or the range isn’t guaranteed, use binary search instead. Key fixes to the original attempt: use while low <= high, compute mid = low + (high - low) // 2 (overflow-safe), compare studentID with arr[mid].studentID, and update low/high accordingly; return -1 if not found. Watch integer division and zero‑based indexing to avoid off‑by‑one errors.

Quick troubleshooting checklist: confirm arr.length == 400; verify arr[0].studentID == 101 and arr[399].studentID == 500; test edge IDs 101 and 500; for binary search, log low, mid, high to see the narrowing. For many repeated lookups where density cannot be assumed, build a hash map (ID → index) for stable O(1) access.

Recommended Answers

All 3 Replies

while(low <= high)/2;

This line has multiple errors. Redo it and recompile.

Write the pseudocode to find the record with a specific studentID

Well, do what the instructions say. If you have a list of numbers, how would you find a specific number?

Assume each number is on 1 index card in a file box. Write down each step (the psuedocode) you use to find the proper card. When your steps work, you have psuedocode that should be easily translatable into C++ Code.

• If all of the elements are in order and the entire array is full wouldn’t you just look at the index of id number - 101?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.