Ds 9queues and RecursionQuickSort
Ds 9queues and RecursionQuickSort
method
Recursive Algorithm
Example
Quick sort complexity
Quick Sort: Example
2
Example of Quick Sort...
3
Quicksort Algorithm
• Input: A[1, …, n]
• Output: A[1, .., n], where A[1]<=A[2]…<=A[n]
• Quicksort:
1. if(n<=1) return;
2. Choose the pivot p = A[n]
3. Put all elements less than p on the left; put all elements lager
than p on the right; put p at the middle. (Partition)
4. Quicksort(the array on the left of p)
5. Quicksort(the array on the right of p)
Quicksort Algorithm
• Quicksort example Current pivots
Previous pivots
2 8 7 1 3 5 6 4
Quicksort
2 1 3 4 7 5 6 8
2 1 3 4 7 5 6 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
Recursive Algorithm cont…
QUICKSORT(A, p, r)
1. if p < r
2. q =PARTITION(A, p, r)
3. QUICKSORT(A, p, q-1)
4. QUICKSORT(A, q +1, r)
5. Exit
Quicksort Algorithm
• Partition example
tail
2 8 7 1 3 5 6 4
tail
2 8 7 1 3 5 6 4 Do nothing
tail
2 8 7 1 3 5 6 4 Do nothing
Quicksort Algorithm
• Partition example
tail
tail
2 1 3 8 7 5 6 4 Do nothing
tail
2 1 3 8 7 5 6 4 Do nothing
i=tail
Complexity of Quick sort
Worst case
O(n2)
Average case
O(n log n)
Best case
O(n log n)
#include<iostream> void QuickSort(int arr[], int p, int r)
{
using namespace std; if (p < r) {
int partition(int arr[], int p, int r)
{ int q = partition(arr,p,r);
int pivot=arr[r];
QuickSort(arr, p, q-1);
int tail=p-1;
for(int j=p; j<r;j++) QuickSort(arr, q + 1, r);
{
}
if(arr[j]<=pivot) }
{ int main()
tail=tail+1; {
int temp= arr[j]; int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
arr[j]=arr[tail];
arr[tail]=temp; cout<<"Given array is \n";
} for(int i=0;i<arr_size;i++)
cout<<arr[i]<<"\t";
}
int temp=arr[r]; QuickSort(arr, 0, arr_size - 1);
arr[r]=arr[tail+1];
arr[tail+1]=temp; cout<<"\nSorted array is \n";
for(int i=0;i<arr_size;i++)
return tail+1; cout<<arr[i]<<"\t";
} return 0;
}
Thank You