You are on page 1of 5

Experiment Title: 3.

Student Name: AMAN SHARMA UID: 19BCS3859


Branch: CSE BIG DATA Lab Group: BD-2(GRP-A)
Semester: 5th Date of Performance: 15-11-21
Subject Name: AP LAB Subject Code: CSP-347

1. Aim/Overview of the practical: Design a quick sort with random pivoting using Lomuto
partition scheme.

2. Task to be done: To write a program in C++ to design a quick sort with random pivoting
using lomuto partition scheme.
.

3. Algorithm/Flowchart (For programming based labs):

partition(arr[], lo, hi)


pivot = arr[hi]
i = lo // place for swapping
for j := lo to hi – 1 do
if arr[j] <= pivot then
swap arr[i] with arr[j]
i=i+1
swap arr[i] with arr[hi]
return i

partition_r(arr[], lo, hi)


r = Random Number from lo to hi
Swap arr[r] and arr[hi]
return partition(arr, lo, hi)

quicksort(arr[], lo, hi)


if lo < hi
p = partition_r(arr, lo, hi)
quicksort(arr, lo , p-1)
quicksort(arr, p+1, hi)

4. Steps for experiment/practical:

#include <cstdlib>
#include <iostream>
using namespace std;

int partition(int arr[], int low, int high)


{
int pivot = arr[low];
int i = low - 1, j = high + 1;

while (true) {

do {
i++;
} while (arr[i] < pivot);

do {
j--;
} while (arr[j] > pivot);

if (i >= j)
return j;

swap(arr[i], arr[j]);
}
}
int partition_r(int arr[], int low, int high)
{

srand(time(NULL));
int random = low + rand() % (high - low);

swap(arr[random], arr[low]);

return partition(arr, low, high);


}

void quickSort(int arr[], int low, int high)


{
if (low < high) {

int pi = partition_r(arr, low, high);

quickSort(arr, low, pi);


quickSort(arr, pi + 1, high);
}
}

void printArray(int arr[], int n)


{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
7. Result/Output/Writing Summary:
Conclusion/ Remarks:

1. Like Merge Sort, QuickSort is a Divide and Conquer algorithm.

2. The key process in quickSort is partition().

3. Target of partitions is, given an array and an element x of array as pivot, put x at its
correct position in sorted array and put all smaller elements (smaller than x) before x, and
put all greater elements (greater than x) after x. All this should be done in linear time.

You might also like