Reputation: 51
I have an array of Students, and I am trying to add another student to the list. I am writing the add method which will add a student to the list in alphabetic order based on their name. All the other elements in the list then will shift accordingly. This is my attempt to write it:
void Array::add(Student* student)
{
if (size == MAX_STUDENTS)
return;
if(size == 0){
students[0] = student;
size ++;
}
if (size != 0){
for(int i = 0; i < MAX_STUDENTS; ++i){
if(students[i]->getName() >= student->getName()){
students[i-1] = student;
size ++;
}
}
}
}
students is an array of pointers to the Student objectStudent** students;
it is initialized in the constructor along with size
This however, does not sort the elements. I am guessing my logic is incorrect. I also do not know how to shift the elements down the array. Any help will be highly appreciated.
Upvotes: 0
Views: 1243
Reputation: 33952
When shifting items down, start with the last item in the list and work your way up to the insertion point. Should be something along the lines of:
int i;
for (i = size - 1; students[i]->getName() >= student->getName(); i--)
{
students[i+1] = students[i];
}
students[i] = student;
size++;
Better approaches are to have Student implement the < operator and use a std::set or std::priority_queue. Why reinvent the wheel?
Upvotes: 1