Thread: bubble sort array in acending and descending order

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    6

    bubble sort array in acending and descending order

    Code:
    #include<iostream>
    using namespace std;
    int main(void)
    {//declaration of variables
    int i;
    int num[10];
    int temp;
    
    
    for (i=0; i<=9; i++)
    {
        cout<<"please enter a number\n";
        cin>>num[i];
    }
    
    cout<<"you entered \t";
    for (i=0; i<=9; i++)
    {
        cout<<num[i]<<"\t";
    }
    cout<<endl;
    /*
    if (i<=-100 || i<=100)
    {
          cout<<" Please insert correct number"<<endl;  
          cin>>i;
    }*/
    
    for(int i=0; i<10; i++) //sort numbers in ascending order
    {
      for(int y=0; y<9; y++)
      {
       if (num[y]<num[y+1])  
       {
        temp=num[y+1];  //swapping
        num[y+1]=num[y];
        num[y]=temp;
       } 
      } 
    }  
    
    cout<<"sorted number in ascending order are\t";
    for (int i=0; i<10; i++)
    { 
        cout<<num[i]<<"\t";
    }
    cout<<endl;
    
    // sort numbers in 
    for(int i=0; i<10; i++)
    {
      for(int y=0; y>i; y++)
      {
       if (num[y]>num[y+1])  
       {
        temp=num[y+1];  //swapping
        num[y+1]=num[y];
        num[y]=temp;
       } 
      } 
    }  
    
    cout<<"sorted number in descending order are\t";
    for (int i=0; i<10; i++)
    { 
        cout<<num[i]<<"\t";
    }
    cout<<endl;
    system("PAUSE");
     return 0;
    }
    
    
    
    above is my half working program, i just couldn't figure out a way to get a ascending sort to work. Can someone give me a hand? thanks

  2. #2
    Registered User
    Join Date
    Oct 2009
    Posts
    17
    Answer available at this link: Bubble Sort

    Look at the middle part of the code where it begins with... while(!sorted) {

    Sorts in ascending order.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    6
    thanks i think i figured it out

Popular pages Recent additions subscribe to a feed