How to print numbers in an array in ascending and descending order???

closed account (3hMz8vqX)
Hi All,

Can you guys give a very simple example of an ascending order program ???

I got this code from the internet . . .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include  <iostream>
using namespace std;
#define   maxsize   100
 
int main()
{
     int temp, i, j, n, list[maxsize];
     cout<<"\n--You are prompted to enter your list size.--";
     cout<<"\n--Then, for your list size, you are prompted to enter--";
     cout<<"\n--the element of your list.--";
     cout<<"\n--Finally your list will be sorted ascending!!!--\n";
     // get the list size...
     cout<<"\nEnter your list size: ";
     cin>>n;
     // prompting the data from user and store it in the list...
     for(i=0; i<n; i++)
     {
            cout<<"Enter list's element #"<<i<<"-->";
            cin>>list[i];
     }
    
     // do the sorting...
     for(i=0; i<n-1; i++)
            for(j=i+1; j<n; j++)
                if(list[i] > list[j])
                {
                     // these three lines swap the elements list[i] and list[j].
                     temp = list[i];
                     list[i] = list[j];
                     list[j] = temp;
                }
     cout<<"\nSorted list, ascending:  ";
     for(i=0; i<n; i++)
            cout<<" "<<list[i];
    cout<<endl;
                   return 0;
}



What is this line of code:

for(j=i+1; j<n; j++)
if(list[i] > list[j])
{
// these three lines swap the elements list[i] and list[j].
temp = list[i];
list[i] = list[j];
list[j] = temp;
}

I dont understand the logic . . .
Can anyone explain this part to me ???

Similarly how do you make a descending order of this ???

Thankyou everyone in advance!

Last edited on
Topic archived. No new replies allowed.