# bubblesort problem

• 02-08-2008
rainman39393
bubblesort problem
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:

Code:

int main()
{
char x='z';
string names[100]={};
int numbers[100]={};
int counter=0;
message();
while(x!='q')
{
x=getcommand();
switch(x)
{
case'a':
case'A':
break;
case'i':
case'I':
displayi(names, numbers, counter);
break;
case'n':
case'N':
displayn(names, numbers, counter);
break;
case'q':
case'Q':
x='q';
break;
default:
cout << "Invalid Input" << endl;
}
}
return 0;
}
void add(string names[], int numbers[], int& counter)
{
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++)
{
if(numbers[i]<numbers[j])
{
int temp= numbers[i];
numbers[i]=numbers[j];
numbers[j]=temp;
}
}
}
for(int f=0;f<counter;f++)
cout<<numbers[f]<<endl;
}

Any suggestions would be great, thanks.
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.
• 02-08-2008
tabstop
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.
• 02-08-2008
iMalc