Our DSA Lab 12
Our DSA Lab 12
Faculty of Engineering
Objective
To develop a code for Quick-sort Algorithm.
Introduction
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into
smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the
specified value, say pivot, based on which the partition is made and another array holds values greater
than the pivot value. Quick sort partitions an array and then calls itself recursively twice to sort the two
resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst
case complexity are of Ο(n2), where n is the number of items.
Based on our understanding of partitioning in quick sort, we will now try to write an algorithm
for it, which is as follows.
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot
Quick Sort Pivot Pseudocode:
leftPointer = left - 1
rightPointer = right
while True do
//do-nothing
end while
//do-nothing
end while
break
else
swap leftPointer,rightPointer
end if
end while
swap leftPointer,right
return leftPointer
end function
To get more into it, let’s see the pseudocode for quick sort algorithm:
if right-left <= 0
return
else
pivot = A[right]
quickSort(left,partition-1)
quickSort(partition+1,right)
end if
end procedure
Tasks:
1. Develop the codes using the provided quick-sort algorithms and print the outputs.
Code:
#include <iostream>
using namespace std;
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
quickSort(arr, 0, n - 1);
return 0;
}
Output: