Quicksort of array in c++

#include <iostream.h>
#include <conio.h>
#define SIZE 10
 
template <class T>
class QSORT
{
   private:   T Array[SIZE];
	      int len;
   public:    QSORT(int);	//constructor
	      void getArray(void);
	      void quickSort(int,int);
	      int partition(int, int);
	      void printArray(void);
};	//End of QSORT class
 
template <class T>
QSORT <T> :: QSORT(int length)
{
    len = length;
 
    //Initialize all array elements to 0
    for (int k = 0; k < len; k++)
    {
	 Array[k] = 0;
    }
}  //End of the constructor function
 
template <class T>
void QSORT <T> :: getArray(void)
{
    cout<<"Enter the elements of an array"<<endl;
    for (int k = 0; k < len; k++)
    {
	 cin>>Array[k];
    }
}	//End of getArray function
 
template <class T>
void QSORT <T> :: quickSort(int low, int high)
{
    int pos;
    if(low < high)
    {
	 pos = partition(low,high);
	 quickSort(low, pos-1);
	 quickSort(pos+1,high);
    }
} 	//End of quickSort function
 
template <class T>
int QSORT <T> :: partition(int low, int high)
{
    T key, temp;
    int left,right, true = 1;
 
    left = low;
    right= high;
    key = Array[low];  // Assume that the first element
		       // is a pivot value
 
    while(true)
    {
	while(left <high && (key >= Array[left]))
	{
	  left++;
	}
 
	while(key < Array[right])
	{
	   right--;
	}
 
	if (left < right)
	{
	   temp = Array[left];
	   Array[left] = Array[right];
	   Array[right]=temp;
	}
	else
	{
	   temp = Array[low];
	   Array[low] = Array[right];
	   Array[right]=temp;
	   return (right);
	}
    }   //End of while
}
 
template <class T>
void QSORT <T> :: printArray(void)
{
    cout<<"Sorted array is "<<endl;
    for (int k = 0; k < len; k++)
    {
	 cout<<Array[k]<<endl;
    }
}	//End of printArray function
 
void main()
{
   int size,low, high;
   clrscr();
 
   cout<<"Enter the size of array"<<endl;
   cin>>size;
 
   low = 0;
   high = size - 1;
 
   QSORT<int> IA(size);
   QSORT<double> DA(size);
 
   cout<<"INTEGER ARRAY PROCESSING..."<<endl;
   IA.getArray();
 
   IA.quickSort(low, high);
   IA.printArray();
 
   cout<<"\nDOUBLE-PRECISION ARRAY PROCESSING..."<<endl;
   DA.getArray();
   DA.quickSort(low, high);
   DA.printArray();
}

Output
Enter the size of array
5
INTEGER ARRAY PROCESSING…
Enter the elements of an array
51
23
78
94
11
Sorted array is
11
23
51
78
94

DOUBLE-PRECISION ARRAY PROCESSING…
Enter the elements of an array
55.67
78.90
23.12
11.555
67.89
Sorted array is
11.555
23.12
55.67
67.89
78.9

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.