MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / partition

Function partition

CPP/sorting/intro_sort.cpp:33–59  ·  view source on GitHub ↗

Function to partition the array using Lomuto partition scheme

Source from the content-addressed store, hash-verified

31
32// Function to partition the array using Lomuto partition scheme
33int partition(int a[], int low, int high)
34{
35 // Pick the rightmost element as a pivot from the array
36 int pivot = a[high];
37
38 // elements less than the pivot will be pushed to the left of `pIndex`
39 // elements more than the pivot will be pushed to the right of `pIndex`
40 // equal elements can go either way
41 int pIndex = low;
42
43 // each time we find an element less than or equal to the pivot, `pIndex`
44 // is incremented, and that element would be placed before the pivot.
45 for (int i = low; i < high; i++)
46 {
47 if (a[i] <= pivot)
48 {
49 swap(a[i], a[pIndex]);
50 pIndex++;
51 }
52 }
53
54 // swap `pIndex` with pivot
55 swap (a[pIndex], a[high]);
56
57 // return `pIndex` (index of the pivot element)
58 return pIndex;
59}
60
61// Quicksort randomized partition to rearrange elements across pivot
62int randPartition(int a[], int low, int high)

Callers 1

randPartitionFunction · 0.70

Calls 1

swapFunction · 0.70

Tested by

no test coverage detected