Presentation is loading. Please wait.

Presentation is loading. Please wait.

Quick Sort.

Similar presentations


Presentation on theme: "Quick Sort."— Presentation transcript:

1 Quick Sort

2 Concept Used What is the concept used in Merge and Quick Sort?
This two sorting techniques use “DIVIDE and CONQUER “ Technique. What is Divide and Conquer Technique? The Problem is divide into similar sub problems When to stop Dividing? When the problem is small enough to be handled. Outline for divide and conquer Sorting ( NEXT )

3 Outline : Divide and conquer Sorting
{ if the list has length greater than 1 then {partition the list into lowlist,highlist; sort(lowlist); sort(highlist); combine(lowlist,highlist); } } Where does the Quick and merge sort differ? They differ in the Way the the List is partitioned

4 Quick Sort Invented by C.A.R Hoare in (Most Popular and widely used) Working: 1. Fix the First Element as the pivot element 2. SCAN L--->R for elements GREATER than PIVOT. Fix it as “i”. 3. SCAN R--->L for elements <= than PIVOT. Fix it as “j”. 4. IF ( I<J) TRUE : SWAP the array values with the index i and j. Continue the process ( GOTO 2 ) FALSE: SWAP the array value at j with the PIVOT. The List is Broken down to two sub list. GOTO 1 for each sub list.

5 Example 75 70 65 84 98 99 100 93 55 61 94 68 I > j<= 75 70 65 68 99 100 93 55 94 84 98 61 98 61 75 70 65 68 100 93 94 84 98 61 99 55 78 55 75 70 65 68 100 93 94 84 98 61 99 55 j i 75 70 65 68 100 93 94 84 98 61 99 55

6 55 70 65 68 61 100 93 99 98 94 84 70 65 68 61 84 93 99 98 94 93 99 98 94 61 65 68 70 93 99 98 94 61 65 68 99 98 94 94 98 99 94 98

7 Full program for QuickSort
#include <iostream.h> #include <conio.h> #define MAX 5 void Swap(int x, int y,int a[]) { int temp; temp=a[x]; a[x]=a[y]; a[y]=temp; }

8 int Partition (int left, int right,int a[])
{ int pivot, pivotpos; pivot=a[left]; pivotpos=left; for(int i=left+1;i<=right;i++) if (a[i]<pivot) Swap(++pivotpos,i,a); //move large entry to right and small to left Swap(left,pivotpos,a); return pivotpos; }

9 void QuickSort (int left,int right,int a[])
{ int pivotpos; if (left<right) pivotpos=Partition(left,right,a); QuickSort(left,pivotpos-1,a); QuickSort(pivotpos+1,right,a); }

10 void main() { int A[MAX],i; clrscr(); cout<<"Enter "<<MAX<<" elements to be sorted:"<<endl; for (i=0;i<MAX;i++) cin>>A[i]; QuickSort(0,MAX-1,A); cout<<"The elements after Quick Sort"<<endl; cout<<A[i]<<endl; }


Download ppt "Quick Sort."

Similar presentations


Ads by Google