I have been writing a bubble sort function to sort an array of numbers and an array of names. I wrote the code the way I thought it was supposed to be but every time I run it, the last input from the array gets changed into a 0 and gets sorted to the front, and I can't figure out the problem. Here is the code:
Any suggestions would be great, thanks.
add(names, numbers, counter);
displayi(names, numbers, counter);
displayn(names, numbers, counter);
cout << "Invalid Input" << endl;
void add(string names, int numbers, int& counter)
cout << "Enter the name: ";
cin >> names[counter];
cout << "Enter the CWID: ";
cin >> numbers[counter];
void displayi(string names, int numbers, int& counter)
int i, j;
for (i=0; i < counter; i++)
for (j=0; j<i; j++)
int temp= numbers[i];
Also, once I fix this problem I have to write the other bubble sort for the names and I was confused about how, if the user selects to sort by number, to have the names sorted as well so they display next to the correct number. Thanks.
The problem with the indices comes from the fact that you increment counter before adding names and IDs to the arrays, rather than after. Array index 0 stays "blank".
And why can't you swap names at the same time you swap numbers?
Edit to add: And while you're at it, you should look up the bubblesort algorithm again.
As tabstop says, the problem is with your 'add' function.
The 'displayi' function is okay. It's not using BubbleSort, but it will sort the numbers array. It's what some call 'SimpleSort'.
You aren't touching the names array. I presume this is because the program is unfinished?
You should look into using to_upper instead of having to code in case statements for both upper and lower case.