• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ Alphabetize function

egeekial

Member
Ok, I have a structure StudentInfo with first and last names in it. I have an array of this type StudentInfo: StudentInfo stud_info[24] (25 different names).

Now I have a function that takes a single element of the array and puts it into the proper place alphabetically and moves everything else to make room. The function takes as inputs (StudentInfo stud_info[24], StudentInfo current, int count). Those being the array of the structure, the current name being inserted, and the count of the current name being inputted.

Well, this is a lot harder than it sounds to code, and it isn't quite working out right. I don't know what the problem is...

 
First, if you have 25 elements in your array, it should be StudentInfo stud_info[25]. Even though your indexes go from 0 to 24, you need to specify the number of elements inside the brackets when declaring the array.

Second, your loop to find the insert position will not find the correct position if you have fewer than 2 elements already in the array, and it will not find the correct position if it is the first or last position in the array. You only need 1 if test (find the first element greater than the one you want to insert), and it should work from there. You can also take the (count == 0) test out of the while loop. If count is 0, simply copy the new record into the first position.
 
Originally posted by: Cerebus451
Second, your loop to find the insert position will not find the correct position if you have fewer than 2 elements already in the array, and it will not find the correct position if it is the first or last position in the array.


How exactly do I go about fixing this?
 
Originally posted by: egeekial
Originally posted by: Cerebus451
Second, your loop to find the insert position will not find the correct position if you have fewer than 2 elements already in the array, and it will not find the correct position if it is the first or last position in the array.


How exactly do I go about fixing this?

Just as the second half of the paragraph suggested. Inside your loop, find the first element that is greater than the one you wish to insert and break out of the loop. If you did not find an element in the list greater than the one you wish to insert, then you will add to the end.
 
Back
Top