Hey guys i'm still having trouble with my bubble sort in else if(choice==2). Where am i going wrong i'm about ready to pull my hair out

#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

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

    cout<< "Please enter 20 integers";
    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 = (n - 1); i >= 0; i--)
            {
                for (j = 1; j <= 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;

                        cout<<"Here are your numbers:"<<tmp<<endl;

                    }
                }
            }
        }

}

Recommended Answers

All 12 Replies

#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

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

	cout<< "Please enter 20 integers";
	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 = (n - 1); i >= 0; i--)
		{
			for (j = 1; j <= 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;

					cout<<"Here are your numbers:"<<tmp<<endl;

				}
			}
		}
	}
}

Line 46: I would not display your numbers in the middle of an if statent inside of a nested for loop. I'm not sure what you are trying to display here, but there is no reason to expect that the numbers outputted in line 46 would be sorted, even if the sorting code is perfect. Display the numbers AFTER the sort is over.

Lines 40, 43 and 44: You are going to get a segmentation fault here if j ever has the value 19.


Also, do you ever look at num[0] anywhere?

Hello Trckst3,

I have noticed some faults in your program code.

1) Firstly you wont be needing the Libraries

#include <iomanip>
#include <algorithm>

In your program.
2) The Bubble Sort Function in your program is faulty.
I will give you a small reference(idea) in which you can proceed in,
Take in the first number and then compare with the next number, If the first is lesser than the second number,then swap the numbers.
num[0] will be num[1] and num [1] will be num[0]. Then compare the current num[0]with num[2] and so on uptil num[19].

Keep repeating the procedure till you compare num[19] with all the other numbers in the array.
Then you will have the Sort.

Hint: You can do this by using 2 "For" loops and 1 different variable in each of the initialisers.

And i prefer that you remove the

cout<<"Here are your numbers:"<<tmp<<endl;

from the nested loops and use the same cout function in

if(choice==1)

Hope you get this done.

I thought bubble sort was more often done using the loop structure:

for(int i = 1; i < N; i++){
   for(int j = 0; j < i; j++){
      if(x[i] < x[j]){
         swap(x[i], x[j]);
         }
      }
   }

because you're only comparing the immediate neighbours x[j] > x[j+1], I'm guessing you're going to need a whole lot more iterations.
you could use your immediate neighbour sort if you change the loops to the order of:

for(int i = 0; i < N; i++){
   for(int j = 0; j < N; j++){

Consider the array [5 4 3 2 1] for ascending sort. How many swaps will it take to get the rightmost 1 into the leftmost position using the immediate neighbour comparision? And what about moving the 5 to the rightmost position? (the same number of swaps, but one is moved 1 position for every inner loop, while the other is moved 1 position for every outer loop). Obviously this method is worse (slower - more iterations) than the one I just posted.

Ok i tried using the immediate neighbor sort like you suggested and it works fine as long as you input the numbers in order from 1-20 it'll assign them fine but if you mix the numbers up and use larger numbers it lists them like 50 times and doesn't put them in any order is it because of the way i have lines 42-46 setup?

Ok i tried using the immediate neighbor sort like you suggested and it works fine as long as you input the numbers in order from 1-20 it'll assign them fine but if you mix the numbers up and use larger numbers it lists them like 50 times and doesn't put them in any order is it because of the way i have lines 42-46 setup?

Post your most recent code. As I mentioned before, if you put your cout statements in the middle of the sort like you have, you are not going to get a display of the sorted numbers even if your sorting code is perfect.

OK here is the newest code i have. so far...still working on it

#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

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

    cout<< "Please enter 20 integers";
    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(int i = 0; i < N; i++){
                for(int j = 0; 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;



                    }
                }
            }
        }

    }
}

OK here is the newest code i have. so far...still working on it

#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;

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

    cout<< "Please enter 20 integers";
    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(int i = 0; i < N; i++){
                for(int j = 0; 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;



                    }
                }
            }
        }

    }}

end quote.

I think you still have the potential segmentation fault here:

            for(int j = 0; j < N; j++){
            {
                if (num[j+1] < num[j])

When j = N - 1, j + 1 = N. num[N] is a segmentation fault since num is only defined for indexes 0 through N - 1. I think you also have an extra bracket in there after the beginning of the j for-loop. Do you intend to have two starting brackerts there?

yeah you're right. I'll blame it on a cut-and-paste error...
I should have written:

for(int i = 0; i < N; i++){
   for(int j = 0; j < N-1; j++){

Hey, what happens if the user chooses option 3?? isn't it supposed to display the numbers?

Look at how i worked out your total program ..

#include <iostream>

using namespace std;

int main ()
{
    cout<< " -==_ Welcome to Bubble Sort_==- \n";
    
    int num[20];
    
    cout<<" Please Enter 20 INTEGERS \n";
    for (int i=0;i<=19;i++)
    {
        cout<<" Enter number :: "<< i+1<<"\n";
        cin >> num[i];
        cout<<"\n"; 
    }
    cout<<" Thanks for the numbers... Lets continue.  \n\n";
    
    for(;;)
    {
    cout<<"\n1.Display original data.\n";
    cout<<"2.Sort the data into Ascending order\n";
    cout<<"3.Display the sorted data (Only if you've already sorted!! Printing will be done in ascending order)\n";
    cout<<"4.Get the address of the first element of array.\n\n";
    cout<<"5. EXIT FROM THE PROGRAM\nEnter your choice ::";
    int j;
    cin >>j;
    
    switch(j)
             {
             case 1:
             for (int b=0;b<=19;b++){cout<<" Entered number  :: "<< b+1<<"="<<num[b]<<"\n";}
             break;
             case 2:
              for(int k = 0;k<=19;k++)
            {
                         for(int m=0;m<=19;m++)
                         {
                                 if(num[k]<=num[m])
                                 {
                                      int sw = num[k];//Values will switch or swap
                                      num[k] = num[m];
                                      num[m] = sw;
                                 }
                         }
            }
            
             for (int c=0;c>=19;c++){cout<<" Sorted number  :: "<< c+1<<"="<<num[c]<<"\n";}
             break;
             case 3:
             for (int d=0;d<=19;d++){cout<<" Sorted number  :: "<< d+1<<"="<<num[d]<<"\n";}
             break;
             case 4:
             cout<<"The address of the first element is:: "<<&num[0]<<"\n";
             break;
             case 5:
             return 0;//Switch of the For ever Loop.          
             default:
             cout<<"Invalid Number "<<"\n";//Error Handling.
             break;
             }
    }     
         
}

Oh man i feel like an idiot i know what i was doing wrong now i was using 20 as my n= and everything else that's why it was messing up i read through your code real quick and i noticed that that was the main difference i chaged it to 19 in my code and voila it worked. THANK YOU!!! I'm gonna have to finish writing it from here but it should be cake from here. Thank you guys so much!!

Well , I am happy that it all has worked out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.