1. ## Bubble sort

Hey guys i'm trying to get the bubble sort to work in my if(choice==2) statement but it's not working right at all. Any ideas?
Thanks!

Code:
```#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

int main()
{
int i,num[20],n,j,choice,tmp;

for (i=0; i<20; i++)
{
cout<<"\nEnter next value:";
cin>>num[i];

}

cout<<"\n1.Display original data.\n";
cout<<"2.Sort the data into descending order\n";
cout<<"3.Display the sorted data (Only if you've already sorted)\n";
cout<<"4.Get the address of the first element of array.\n\n";
cin>>choice;

if (choice==1)
{

for (i=0; i<20; i++)
{
cout<<"\n"<<num[i]<<endl;
}
return 0;
}
else if (choice==2)
{
n=20;
for (i=0; i<n; i++)
{
for (j=0; j<n-i; j++)
{
if (num[j+1] < num[j])    /* compare the two neighbors */
{
tmp = num[j];         /* swap a[j] and a[j+1]      */
num[j] = num[j+1];
num[j+1] = tmp;

}
}
}
}

}```

2. Overflow. (j=i=19+1)

Soma

3. Originally Posted by Trckst3
Hey guys i'm trying to get the bubble sort to work in my if(choice==2) statement but it's not working right at all. Any ideas?
Thanks!

Code:
```#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

int main() {
int i,num[20],n,j,choice,tmp;

for (i=0; i<20; i++) {
cout<<"\nEnter next value:";
cin>>num[i];

}

cout<<"\n1.Display original data.\n";
cout<<"2.Sort the data into descending order\n";
cout<<"3.Display the sorted data (Only if you've already sorted)\n";
cout<<"4.Get the address of the first element of array.\n\n";
cin>>choice;

if (choice==1) {

for (i=0; i<20; i++) {
cout<<"\n"<<num[i]<<endl;
}
return 0;
} else if (choice==2) {
n=20;
for (i=0; i<=n; i++) {
for (j=i; j<=n; j++) {
if (num[j+1] < num[j]) {  /* compare the two neighbors */
tmp = num[j];         /* swap a[j] and a[j+1]      */
num[j] = num[j+1];
num[j+1] = tmp;

}
}
}
}
}```
Just cleaning up your formatting there a bit.

The problem is in your two loops. You have to check the extremes and you'll find that you're checking data outside the loop. Changing the '<'s to '<='s should fix the problem. But I haven't run it so I may have gone the wrong direction. That is to say I maybe should have suggested the 'n's in your for statements be 'n-1's. I'm kinda groggy right now, so I can't think.

4. Also:
You are missing a main loop. How do you expect to enter 1 and then enter 2? That return statement wont play nicely with a loop either.
Case 3 is the same as case 1.
What do you expect number 4 to do? It seems pretty pointless to me.

This should not be there, you need to remove it.
Code:
`                        cout<<"Here are your numbers:"<<tmp<<endl;`