I am practicing inserting and shifting arrays, I have a Contacts program and currently trying to write a function for adding a contact and inserting that contact in the correct position based on their last name
Note: I do not need to do any checks, checks are all done previously before reaching this function, simply insert and shift.
The structure I'm working with:
struct contact{
char firstName[MAXCHAR];
char lastName[MAXCHAR];
char phoneNum[MAXCHAR];
char email[MAXCHAR];
Group group;
};
My Function:
void addContact(contact contacts[],int &numContacts, contact &aContact) {
int index = 0;
int insertIndex = numContacts;
for (int i = 0; i < numContacts; i++){
if(aContact.lastName < contacts[i].lastName){
insertIndex = i;
break;
}
}
for (int index = numContacts; index > insertIndex; --index) {
contacts[index] = contacts[index - 1];
}
contacts[insertIndex] = aContact;
numContacts++;
}
aContact is the contact to be added.
numContacts is thee number of contacts currently
contacts[] is the array that needs to be inserted into.
Let's say, contacts[] currently has 3 elements from top down :
Ahmed;Asaf;971-111-9999;asafa@gmail.com;3
Alex;Smith;503-222-4444;alex.smith@gmail.com;0
Anna;White;503-222-1111;annaw@gmail.com;1
and aContacts has:
Rekha;Kaur;503-111-2222;kaurr@gmail.com;2
I would like aContacts to be inserted into the contacts[] by the last name.
Ahmed;Asaf;971-111-9999;asafa@gmail.com;3
Rekha;Kaur;503-111-2222;kaurr@gmail.com;2
Alex;Smith;503-222-4444;alex.smith@gmail.com;0
Anna;White;503-222-1111;annaw@gmail.com;1