You are on page 1of 4

Here you will get program for quick sort in C++.

Quick Sort is one of the most efficient sorting algorithm whose best, worst and
average case time complexities are O (n log n), O (n2) and O (n log n) respectively.

How it works?

1. We first pick a pivot element. There are various ways to pick a pivot element.

 Pick first element


 Pick last element
 Pick a random element
 Pick median element
So we can use anyone of above methods to pick the pivot element. In the program
given below I have picked first element as pivot.

2. Now all the elements smaller than pivot are placed at its left while elements
bigger are placed at right.

3. Repeat the above two steps recursively for both half.

Below is the program to implement this algorithm in C++.

#include <iostream>

using namespace std;

void quick_sort(int[],int,int);
int partition(int[],int,int);

int main()
{
int a[50],n,i;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter array elements:";

for(i=0;i<n;i++)
cin>>a[i];

quick_sort(a,0,n-1);
cout<<"\nArray after sorting:";

for(i=0;i<n;i++)
cout<<a[i]<<" ";

return 0;
}

void quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;

do
{
do
i++;

while(a[i]<v&&i<=u);

do
j--;
while(v<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);

a[l]=a[j];
a[j]=v;

return(j);
}

Output:

How many elements? 6


Enter array elements: 9 15 6 7 10 12
Array after sorting: 6 7 9 10 12 15

2. 2. Write a programme in C++ to find the sum of three numbers using pointer to
function method.

To add two numbers using pointer in C++ Programming, you have to ask to the user to
enter the two number, then make two pointer type variable of same type say *ptr1, *ptr2
& *ptr3 to initialize the address of both the number and make another variable
say sum which contain the addition of the two number like sum = *ptr1 + *ptr2 +*ptr3 and
display the result on the screen.

Here * is also called as value at address operator.

Following C++ program ask to the user to enter the three number and add the entered three
number using pointer then display the addition result on the screen:
/* Program to find largest of three numbers using pointers */
#include<stdio.h>
#include<conio.h>
void main()
{
int x, y, z;
int *a, *b, *c;
printf("\n Enter three numbers:");
scanf("%d%d%d",&x, &y, &z);
a = &x;
b = &y;
c = &z;
if(*a > *b)
{
if(*a > *c)
{
printf("\n %d is larger than %d and %d", *a, *b, *c);
}
else
{
printf("\n %d is larger than %d and %d", *c, *a, *b);
}
}
else
{
if(*b > *c)
{
printf("\n %d is larger than %d and %d", *b, *a, *c);
}
else
{
printf("\n %d is larger than %d and %d", *c, *a, *b);
}
}
getch();
}

OutPut:-

Enter the three no.- 400,20 & 300


400 is larger than 20 & 300

You might also like