Nick Nick - 1 month ago 9
C++ Question

c++ sort(ascending,descending) integer array

So i'm new in C++ and i'm trying some beginner exercises here is the problem : i have to order an integer array in ascending and descending order but every time i try the ascending order there is a 0 appearing out of nowhere inside my array replacing a previous array integer. This is happening only when i use the "ascending order" option. I've tried rearranging the numbers inside the array and changing them but the same thing happens i really can't figure out the problem.I would appreciate some help and i hope my question is not dumb and waste your time.

#include<iostream>
using namespace std;

int main()
{

int i,y,choice,temp,am[5]={8,6,10,7,9};

cout<<"Choice 1 : Descending\nChoice 2 : Ascending\n";
cin>>choice;

if(choice==1)
{
for(i=0;i<5;i++)
{
y=i+1;
while(y<5)
{
while(am[i]<am[y])
{
temp=am[i];
am[i]=am[y];
am[y]=temp;
y++;
}
y++;
}
}
}
else if(choice==2)
{
for(i=0;i<5;i++)
{
y=i+1;
while(y<5)
{
while(am[i]>am[y])
{
temp=am[i];
am[i]=am[y];
am[y]=temp;
y++;
}
y++;
}
}
}
else
cout<<"Error\n";

for(i=0;i<5;i++)
cout<<"am[i]:"<<am[i]<<"\n";

return 0;
}


here is what i see in cmd

Answer

You are using Selection Sort. Your program has 4 errors. Use 'if' instead of while.

#include<iostream>
using namespace std;

int main()
{
    int i,y,choice,temp,am[5]={8,6,10,7,9};

    cout<<"Choice 1 : Descending\nChoice 2 : Ascending\n";
    cin>>choice;

    if(choice==1)
    {
        for(i=0;i<5;i++)
        {
            y=i+1;
            while(y<5)
            {
                if(am[i]<am[y])    //Correction1
                {
                    temp=am[i];
                    am[i]=am[y];
                    am[y]=temp;
                    //y++;         //Correction2
                }
                y++;
            }
        }
    }
    else if(choice==2)
    {
        for(i=0;i<5;i++)
        {
            y=i+1;
            while(y<5)
            {
                if(am[i]>am[y])      //Correction3
                {
                    temp=am[i];
                    am[i]=am[y];
                    am[y]=temp;     
                    //y++;          //Correction4
                }
                y++;
            }
        }
    }
    else
        cout<<"Error\n";

    for(i=0;i<5;i++)
        cout<<"am[i]:"<<am[i]<<"\n";

    return 0;
}