How to Sort Array in C++

Array Sorting is an Important term in Programming. An Array Consists of Indexing which start from 0. To Sort the Values of the Array we use Bubble Sorting Method which compare the Different numbers of array and replace them in Ascending or Descending order. To change order from Ascending to Descending just change the Arithmetic Operator From < to >.

Source Code

#include <iostream>
#include <iomanip>
using namespace std;

 int main()
 {
   const int arraySize = 10;     // size of array a
   int data[ arraySize ];    //Declare the Array
   int insert;      // temporary variable to hold element to insert
  cout<<endl<<endl<<setw(45)<<"************* SORTING THE ARRAY ***********"<<endl<<endl;
  
   // output original array
   for ( int i = 0; i < arraySize; i++ )
   {
    cout<<endl<<setw(15)<<"Enter Number "<<i<<":";
    cin>>data[i];
   }
   for ( int i = 0; i < arraySize; i++ )
   {
     cout << setw( 4 ) << data[ i ];
   }  
   
   for ( int next = 1; next < arraySize; next++ )
   {
    insert = data[ next ];           // store the value in the current element
  
   int moveItem = next;            // initialize location to place element
  
                   // search for the location in which to put the current element
    while ( ( moveItem > 0 ) && ( data[ moveItem - 1 ] > insert ) )
   {
                   // shift element one slot to the right
   data[ moveItem ] = data[ moveItem - 1 ];
   moveItem--;
   }     // end while
  
   data[ moveItem ] = insert; // place inserted element into the array
   } // end for
    cout<<endl<<endl<<setw(45)<<"************* SORTED ARRAY ***********"<<endl<<endl;
  
                     // output sorted array
   for ( int i = 0; i < arraySize; i++ )
   cout << setw( 4 ) << data[ i ];
  
   cout << endl;
   return 0; // indicates successful termination }

Output of the Program 


Sorted array id Displayed



Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments:

  1. excellent explanation of problem and good way of good coding ... keep working

    ReplyDelete