0% found this document useful (0 votes)
30 views

Partitioning: //function For Array

The document contains code for implementing the quicksort algorithm in C++. Quicksort is a divide and conquer algorithm that works by selecting a pivot element and partitioning the array around it, placing all elements less than the pivot to the left and greater elements to the right. It then recursively sorts the subarrays. The code defines functions for partitioning the array and recursively calling quicksort on the subarrays. It takes an array as input, partitions it using quicksort, and prints the sorted output array.

Uploaded by

brainyhamza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Partitioning: //function For Array

The document contains code for implementing the quicksort algorithm in C++. Quicksort is a divide and conquer algorithm that works by selecting a pivot element and partitioning the array around it, placing all elements less than the pivot to the left and greater elements to the right. It then recursively sorts the subarrays. The code defines functions for partitioning the array and recursively calling quicksort on the subarrays. It takes an array as input, partitions it using quicksort, and prints the sorted output array.

Uploaded by

brainyhamza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include<iostream>

#include<conio.h>
using namespace std;
//Function for partitioning array
int part(int low,int high,int *a)
{
int i,h=high,l=low,p,t; //p==pivot
p=a[low];
while(low<high)
{
while(a[l]<p)
{
l++;
}
while(a[h]>p)
{
h--;
}
if(l<h)
{
t=a[l];
a[l]=a[h];
a[h]=t;
}
else
{
t=p;
p=a[l];
a[l]=t;
break;
}
}
return h;
}
void quick(int l,int h,int *a)
{
int index,i;
if(l<h)
{
index=part(l,h,a);
quick(l,index-1,a);
quick(index+1,h,a);
}
}
int main()
{
int a[100],n,l,h,i;
cout<<"Enter number of elements:";
cin>>n;
cout<<"Enter the elements (Use Space As A Separator):";

for(i=0;i<n;i++)
cin>>a[i];
cout<<"\nInitial Array:\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
h=n-1;
l=0;
quick(l,h,a);
cout<<"\nAfter Sorting:\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
return 0;
}
Screenshot:

Worst case

O(n2)

performance
Best case performance

O(n log n) (simple partition)


or O(n) (three-way partition and
equal keys)

Average case

O(n log n)

performance
Worst case space

O(n) auxiliary (naive)

complexity

O(log n) auxiliary (Sedgewick


1978)

You might also like