Program To Sort Given Numbers Using Quick Sort

//   Program To Sort Given Numbers Using Quick Sort

#include<iostream.h>
#include<conio.h>

class quick
{
	private:
		int q[20],n;
		void quicksort(int,int);
	public:
		void qsort();
		void setdata();
		void getdata();
};


void quick::qsort()
{
	quicksort(0,n-1);
}

void quick::quicksort(int left,int right)
{
	int i,j,k,t;

	if(left<right)
	{
		i=left+1;
		j=right;
		k=q[left];

		while(i<=j)
		{
			while(q[i]<k && i<right)
				i++;
			while(q[j]>k && j>left)
				j--;
			if(i<j)
			{
				q[i]=q[i]+q[j];
				q[j]=q[i]-q[j];
				q[i]=q[i]-q[j];
			}
			else
				break;
		}
		t=q[left];
		q[left]=q[j];
		q[j]=t;

		quicksort(left,j-1);
		quicksort(j+1,right);
	}
}

void quick::setdata()
{
	int i;

	cout<<"\n\n\nEnter the size of array : ";
	cin>>n;

	cout<<"\nEnter "<<n<<" elements: ";
	for(i=0;i<n;i++)
	    cin>>q[i];
}

void quick::getdata()
{
	int i;

	for(i=0;i<n;i++)
	    cout<<q[i]<<"\t";
}

void main()
{
	quick q;
	clrscr();


	q.setdata();

	cout<<"\nElements before sorting are : \t";
	q.getdata();

	q.qsort();

	cout<<"\n\nElements after sorting are : \t";
	q.getdata();

	getch();

}


Chitra
Chitra

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in