Presentation is loading. Please wait.

Presentation is loading. Please wait.

Quick Sort. Concept Used What is the concept used in Merge and Quick Sort? This two sorting techniques use “DIVIDE and CONQUER “ Technique. What is Divide.

Similar presentations


Presentation on theme: "Quick Sort. Concept Used What is the concept used in Merge and Quick Sort? This two sorting techniques use “DIVIDE and CONQUER “ Technique. What is Divide."— 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 Sort ( ) {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 1960. (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 ExampleExample 9861 75706584989910093556194687570656899100935594849861 7855 7570656810093948498619955 7570656810093948498619955 ji 75 70656810093948498619955 j<= I >

6 70656861 55 70 656861 706568 61 65 68 1009394849899 9394849899 93949899 93 949899 949899 9498 99 9498 61

7 Full program for QuickSort #include #include #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; for (i=0;i<MAX;i++) cout<<A[i]<<endl;}


Download ppt "Quick Sort. Concept Used What is the concept used in Merge and Quick Sort? This two sorting techniques use “DIVIDE and CONQUER “ Technique. What is Divide."

Similar presentations


Ads by Google