Friday 19 July 2013

08. Write a C++ program to sort a list of numbers in ascending order.

Description about sorting technique: (Bubble Sort)
          Compare each element with remaining elements in the list
          During comparison if the preceding element is small then we will swap
          So that the Biggest element will reach to higher bound of array
          Repeat this process excluding higher most boundary

#include<iostream>
#define SIZE 50      /*Macro used to modify the size of array Based on requirement 

Mechanism of Sorting

                                 No need to traverse or Disturb the program */

using namespace
std;
void
sort(int a[SIZE],int n)
{
    int i,pass,t;   
    for(pass=1;pass<n;++pass)
    {
        for(i=0;i<n-pass;++i)
        {
            if(a[i]>a[i+1])        //swap the two numbers
            {
                t=a[i];
                a[i]=a[i+1];
                a[i+1]=t;
            }
        }
    }
}

int main()
{
    int a[SIZE],n,i;
    cout<<"enter n value";
    cin>>n;
    cout<<"\nenter array values";
    for(i=0;i<n;++i)
        cin>>a[i];           
    cout<<"\narray before sorting : \n";
    for(i=0;i<n;++i)
        cout<<"\n"<<a[i];
    sort(a,n);                 //Array itself is the address of the storage location ( no need of referencing )
    cout<<"\narray after sorting: \n";
    for(i=0;i<n;++i)
        cout<<"\n"<<a[i];
    return 0;
}

No comments:

Post a Comment