Thursday 26 June 2014

C++ program to sort an array

Here are two C++ program to sort an array. First program sort the array in ascending order and second program sort the array in descending order.


Method 1 : C++ program sort the array in ascending order
#include<iostream>
using namespace std;
int main()
{
    int a[20],num,n,temp;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements ";
    for(int i=0;i<num;i++)
       cin>>a[i];
    for(int i=0;i<num-1;i++)
    {
        for(int y=0;y<num-1;y++)
        {
            if(a[y]>a[y+1])
            {
                temp=a[y];
                a[y]=a[y+1];
                a[y+1]=temp;
            }
        }
    }
    cout<<"After sorting : ";
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
    return 0;
}

OUTPUT




Method 2 : C++ program sort the array in descending order
#include<iostream>
using namespace std;
int main()
{
    int a[20],num,n,temp;
    cout<<"How many elements to be stored (max 20) : ";
    cin>>num;
    cout<<"Enter elements ";
    for(int i=0;i<num;i++)
       cin>>a[i];
    for(int i=0;i<num-1;i++)
    {
        for(int y=0;y<num-1;y++)
        {
            if(a[y]<a[y+1])
            {
                temp=a[y];
                a[y]=a[y+1];
                a[y+1]=temp;
            }
        }
    }
    cout<<"After sorting : ";
    for(int i=0;i<num;i++)
        cout<<a[i]<<" ";
    return 0;
}

OUTPUT




Method 3 : C++ program to sort numbers using pointers
#include<iostream>
using namespace std;
int main()
{
    int *p,n,temp;
    cout<<"How many elements to be entered : ";
    cin>>n;
    p=new int[n];
    cout<<"Enter elements : ";
    for(int i=0;i<n;i++)
        cin>>p[i];
    for(int i=0;i<n;i++)
        for(int y=0;y<n-1;y++)
            if(p[y]>p[y+1])
            {
               temp=p[y];
               p[y]=p[y+1];
               p[y+1]=temp;
            }
    cout<<"Sorted array : ";
    for(int i=0;i<n;i++)
        cout<<p[i]<<" ";
    return 0;
}

OUTPUT




Method 4 : C++ program to sort numbers using functions
#include<iostream>
using namespace std;
void sort(int (&)[20],int );
int main()
{
    int n,a[20];
    cout<<"How many elements to be entered : ";
    cin>>n;
    cout<<"Enter elements : ";
    for(int i=0;i<n;i++)
        cin>>a[i];
    sort(a,n);
    cout<<"After sorting : ";
    for(int i=0;i<n;i++)
        cout<<a[i]<<" ";
    return 0;
}
void sort(int (&a)[20],int n)
{
    int temp;
    for(int i=0;i<n;i++)
    {
        for(int y=0;y<n-1;y++)
        {
            if(a[y]>a[y+1])
            {
                temp=a[y];
                a[y]=a[y+1];
                a[y+1]=temp;
            }
        }
    }
}

OUTPUT




No comments:

Post a Comment