Wednesday, 5 September 2012

sorting array using pointer


#include<iostream>
using std::cin;
using std::cout;
#include<conio.h>
void main()
{
            int *p,n,a[100],i,*j,t;
            cout<<"enter the no of elements: ";
            cin>>n;
            cout<<"\nenter the elements-\n";
            for(i=0;i<n;i++)
            {
                        cin>>a[i];
            }
            for(p=&a[0];p<=&a[n-1];p++)
            {
                        for(j=&a[0];j<=&a[n-1];j++)
                        {
                                    if(*p>*j)
                                    {
                                                t=*p;
                                                *p=*j;
                                                *j=t;
                                    }
                        }
            }
            cout<<"\nthe sorted elements are: ";
            for(p=&a[0];p<=&a[n-1];p++)
            {
                        cout<<*p<<" ";
            }
            getch();
}
           
Output:
enter the no of elements: 8

enter the elements-
-1 0 9 99 -45 5 6 3

the sorted elements are: 99 9 6 5 3 0 -1 -45

No comments:

Post a Comment