Showing posts with label Array Sorting. Show all posts
Showing posts with label Array Sorting. Show all posts

Thursday, 17 July 2014

How to Sort Array in C++

1.  Sort Array in Ascending Order
2.  Sort Array in Descending Order

Structure of the Problem Requirements 

Array Sorting is an Important term in Programming which is use in every where. An Array Consist 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
Sorted Array