// 7} WAP to print number in ascending order using array.
//Asending Order
#include<iostream.h>
#include<conio.h>
void main()
{
int a[100];
int i,j,n,temp;
clrscr();
cout<<"How Many Numbers?"<<endl;
cin>>n;
cout<<"Enter The Elements"<<endl;
for(i=0;i<=n-1;++i)
{
cin>>a[i];
}
for(i=0;i<=n-1;++i)
{
for (j=0;j<=n-1;++j)
{
if (a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"Asending Order"<<endl;
for(i=0;i<=n-1;++i)
{
cout<<a[i]<<'\t';
}
cout<<endl;
getch();
}
There’s a well known algorithm very close to the one you chose called “BubbleSort”.
The main difference is that it repeatedly checks if the array is already sorted and exits as soon as it realizes it is. This way, it avoids pointless iterations.
Example of BubbleSort algorithm with already sorted array:
How Many Numbers? 5
Enter the elements separated by spaces: 1 2 3 4 5
Ascending Order:
1 2 3 4 5
It took me 4 iteration.
While with your code the above sorting results in:
How Many Numbers? 5
Enter the elements separated by spaces: 1 2 3 4 5
Ascending Order:
1 2 3 4 5
It took me 25 iteration.
If you want to do your own sort, I highly recommend shell sort, which is extremely efficient and
the code is virtually identical to the simple sorts (insertion, bubble, etc) in difficulty to write. It is a little challenging to understand its big-O but take it on faith that it runs @ N( (C+1)/C) run time, typical implementations get N(7/6) run time.
If you are sorting more than several million items, quicksort will overtake it somewhere in that range. Quicksort is a pain to write correctly, as it will use... a copy of shell sort when the split lists become small enough from the recursion, or some people use insertion there.