TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sorting Namespace Reference

for working with vectors More...

Functions

template<class T >
int64_t binary_search (std::vector< T > &arr, T val, int64_t low, int64_t high)
 Binary search function to find the most suitable pace for an element.
 
template<typename T >
void insertionSort_binsrch (std::vector< T > &arr)
 Insertion sort function to sort the vector.
 
template<typename T , size_t N>
std::array< T, N > shuffle (std::array< T, N > arr)
 
template<typename T , size_t N>
std::array< T, N > randomized_bogosort (std::array< T, N > arr)
 
template<typename T >
void gnomeSort (T *arr, int size)
 
template<typename T , size_t size>
std::array< T, size > gnomeSort (std::array< T, size > arr)
 
template<typename T >
void insertionSort (T *arr, int n)
 Insertion Sort Function.
 
template<typename T >
void insertionSort (std::vector< T > *arr)
 Insertion Sort for a vector.
 
template<class Iterator >
void merge (Iterator l, Iterator r, const Iterator e, char b[])
 merges 2 sorted adjacent segments into a larger sorted segment
 
template<class Iterator >
void non_recursive_merge_sort (const Iterator first, const Iterator last, const size_t n)
 bottom-up merge sort which sorts elements in a non-decreasing order
 
template<class Iterator >
void non_recursive_merge_sort (const Iterator first, const size_t n)
 bottom-up merge sort which sorts elements in a non-decreasing order
 
template<class Iterator >
void non_recursive_merge_sort (const Iterator first, const Iterator last)
 bottom-up merge sort which sorts elements in a non-decreasing order
 
template<std::size_t N>
std::array< int, N > pigeonSort (std::array< int, N > arr)
 
template<typename T >
void quicksort (std::vector< T > *arr, int32_t low, int32_t high)
 
template<typename T >
std::vector< T > quicksort (std::vector< T > arr, int32_t low, int32_t high)
 
int partition (std::vector< int > &arr, int start, int end)
 The partition function sorts the array from start to end and uses the last element as the pivot.
 
void iterativeQuickSort (std::vector< int > &arr)
 The main sorting function.
 
template<typename T >
void recursive_bubble_sort (std::vector< T > *nums, uint64_t n)
 This is an implementation of the recursive_bubble_sort. A vector is passed to the function which is then dereferenced, so that the changes are reflected in the original vector. It also accepts a second parameter of type int and name n, which is the size of the array.
 
std::vector< uint64_t > selectionSort (const std::vector< uint64_t > &arr, uint64_t len)
 
template<typename T >
void shell_sort (T *arr, size_t LEN)
 
template<typename T , size_t N>
void shell_sort (T(&arr)[N])
 
template<typename T >
void shell_sort (std::vector< T > *arr)
 

Detailed Description

for working with vectors

for io operations

for returning multiple values form a function at once

header files

Sorting Algorithms.

for std::assert

for using std::vector

for assert

for std::vector

Sorting algorithms.

for algorithm functions for assert for IO operations

Sorting algorithms

for std::is_sorted for assert for IO implementations for std::string for std::pair, std::swap for std::vector, std::vector::push_back, std::vector::size

for assert for typedef datatype uint64_t for IO operations

Sorting algorithms

for std::is_sorted, std::swap for io operations for std::vector

Sorting algorithms

for std::is_sorted for std::swap and io operations for std::vector

@breif Sorting algorithms

Sorting algorithms

for std::is_sorted for assert function in testing for std::cout and std::endl

Contains sorting algorithms

for std::is_sorted for std::time for IO operations for std::vector

Sorting algorithms

for std::cout for std::vector for std::stack for std::is_sorted for assert

for collection of functions for a macro called assert which can be used to verify assumptions for io operations for std::vector

Sorting algorithms

for std::is_sorted(), std::swap() for std::array for assert for initializing random number generator for IO operations

Sorting algorithms

for std::is_sorted for std::array for IO operations for std::vector

Sorting algorithms

for std::is_sorted for IO operations for std::vector

for std::is_sorted for assert for std::swap and io operations

Sorting algorithms

for std::is_sorted, std::swap for assert for IO operations

Sorting algorithms

Function Documentation

◆ binary_search()

template<class T >
int64_t sorting::binary_search ( std::vector< T > & arr,
T val,
int64_t low,
int64_t high )

Binary search function to find the most suitable pace for an element.

Template Parameters
TThe generic data type.
Parameters
arrThe actual vector in which we are searching a suitable place for the element.
valThe value for which suitable place is to be found.
lowThe lower bound of the range we are searching in.
highThe upper bound of the range we are searching in.
Returns
the index of most suitable position of val.

Definition at line 63 of file binary_insertion_sort.cpp.

63 {
64 if (high <= low) {
65 return (val > arr[low]) ? (low + 1) : low;
66 }
67 int64_t mid = low + (high - low) / 2;
68 if (arr[mid] > val) {
69 return binary_search(arr, val, low, mid - 1);
70 } else if (arr[mid] < val) {
71 return binary_search(arr, val, mid + 1, high);
72 } else {
73 return mid + 1;
74 }
75}
int64_t binary_search(std::vector< T > &arr, T val, int64_t low, int64_t high)
Binary search function to find the most suitable pace for an element.

◆ gnomeSort() [1/2]

template<typename T , size_t size>
std::array< T, size > sorting::gnomeSort ( std::array< T, size > arr)

This implementation is for a C++-style array input. The function argument is a pass-by-value and hence a copy of the array gets created which is then modified by the function and returned.

Template Parameters
Ttype of data variables in the array
sizesize of the array
Parameters
[in]arrour array of elements.
Returns
array with elements sorted

Definition at line 62 of file gnome_sort.cpp.

62 {
63 // few easy cases
64 if (size <= 1) {
65 return arr;
66 }
67
68 int index = 0; // initialize loop index
69 while (index < size) {
70 // check for swap
71 if ((index == 0) || (arr[index] >= arr[index - 1])) {
72 index++;
73 } else {
74 std::swap(arr[index], arr[index - 1]); // swap
75 index--;
76 }
77 }
78 return arr;
79}

◆ gnomeSort() [2/2]

template<typename T >
void sorting::gnomeSort ( T * arr,
int size )

This implementation is for a C-style array input that gets modified in place.

Parameters
[in,out]arrour array of elements.
sizesize of given array

Definition at line 34 of file gnome_sort.cpp.

34 {
35 // few easy cases
36 if (size <= 1) {
37 return;
38 }
39
40 int index = 0; // initialize some variables.
41 while (index < size) {
42 // check for swap
43 if ((index == 0) || (arr[index] >= arr[index - 1])) {
44 index++;
45 } else {
46 std::swap(arr[index], arr[index - 1]); // swap
47 index--;
48 }
49 }
50}

◆ insertionSort() [1/2]

template<typename T >
void sorting::insertionSort ( std::vector< T > * arr)

Insertion Sort for a vector.

Insertion Sort Function

Template Parameters
Ttype of array
Parameters
[in,out]arrpointer to array to be sorted
Template Parameters
TType of the vector elements
Parameters
[in,out]arrPointer to the vector to be sorted

Definition at line 77 of file insertion_sort.cpp.

77 {
78 size_t n = arr->size();
79
80 for (size_t i = 1; i < n; i++) {
81 T temp = arr[0][i];
82 int32_t j = i - 1;
83 while (j >= 0 && temp < arr[0][j]) {
84 arr[0][j + 1] = arr[0][j];
85 j--;
86 }
87 arr[0][j + 1] = temp;
88 }
89}

◆ insertionSort() [2/2]

template<typename T >
void sorting::insertionSort ( T * arr,
int n )

Insertion Sort Function.

Template Parameters
Ttype of array
Parameters
[in,out]arrArray to be sorted
nSize of Array
Template Parameters
TType of the array elements
Parameters
[in,out]arrArray to be sorted
nSize of the array

Definition at line 59 of file insertion_sort.cpp.

59 {
60 for (int i = 1; i < n; i++) {
61 T temp = arr[i];
62 int j = i - 1;
63 while (j >= 0 && temp < arr[j]) {
64 arr[j + 1] = arr[j];
65 j--;
66 }
67 arr[j + 1] = temp;
68 }
69}

◆ insertionSort_binsrch()

template<typename T >
void sorting::insertionSort_binsrch ( std::vector< T > & arr)

Insertion sort function to sort the vector.

Template Parameters
TThe generic data type.
Parameters
arrThe actual vector to sort.
Returns
Void.

Definition at line 84 of file binary_insertion_sort.cpp.

84 {
85 int64_t n = arr.size();
86
87 for (int64_t i = 1; i < n; i++) {
88 T key = arr[i];
89 int64_t j = i - 1;
90 int64_t loc = sorting::binary_search(arr, key, 0, j);
91 while (j >= loc) {
92 arr[j + 1] = arr[j];
93 j--;
94 }
95 arr[j + 1] = key;
96 }
97}

◆ iterativeQuickSort()

void sorting::iterativeQuickSort ( std::vector< int > & arr)

The main sorting function.

The iterative quick sort uses the stack instead of recursion for saving and restoring the environment between calls. It does not need the end and start params, because it is not recursive.

Parameters
arrarray to be sorted
Returns
void

Definition at line 58 of file quick_sort_iterative.cpp.

59{
60 std::stack<int> stack;
61 int start = 0;
62 int end = arr.size()-1;
63 stack.push(start);
64 stack.push(end);
65
66 while(!stack.empty())
67 {
68 end = stack.top();
69 stack.pop();
70 start = stack.top();
71 stack.pop();
72
73 int pivotIndex = partition(arr,start,end);
74
75 if(pivotIndex -1 > start)
76 {
77 stack.push(start);
78 stack.push(pivotIndex-1);
79 }
80
81 if(pivotIndex+1<end)
82 {
83 stack.push(pivotIndex+1);
84 stack.push(end);
85 }
86 }
87}
for std::invalid_argument
Definition stack.hpp:19
void pop()
Definition stack.hpp:62
void push(const value_type &item)
Definition stack.hpp:47
value_type top() const
Definition stack.hpp:56
char stack[MAX]

◆ merge()

template<class Iterator >
void sorting::merge ( Iterator l,
Iterator r,
const Iterator e,
char b[] )

merges 2 sorted adjacent segments into a larger sorted segment

best-case = worst-case = O(n)

Parameters
lpoints to the left part
rpoints to the right part, end of left part
epoints to end of right part
bpoints at the buffer

Definition at line 57 of file non_recursive_merge_sort.cpp.

57 {
58 // create 2 pointers to point at the buffer
59 auto p(reinterpret_cast<std::remove_reference_t<decltype(*l)>*>(b)), c(p);
60 // move the left part of the segment
61 for (Iterator t(l); r != t; ++t) *p++ = std::move(*t);
62 // while neither the buffer nor the right part has been exhausted
63 // move the smallest element of the two back to the container
64 while (e != r && c != p) *l++ = std::move(*r < *c ? *r++ : *c++);
65 // notice only one of the two following loops will be executed
66 // while the right part hasn't bee exhausted, move it back
67 while (e != r) *l++ = std::move(*r++);
68 // while the buffer hasn't bee exhausted, move it back
69 while (c != p) *l++ = std::move(*c++);
70}

◆ non_recursive_merge_sort() [1/3]

template<class Iterator >
void sorting::non_recursive_merge_sort ( const Iterator first,
const Iterator last )

bottom-up merge sort which sorts elements in a non-decreasing order

Parameters
firstpoints to the first element
lastpoints to 1-step past the last element

Definition at line 86 of file non_recursive_merge_sort.cpp.

86 {
87 non_recursive_merge_sort(first, last, last - first);
88}

◆ non_recursive_merge_sort() [2/3]

template<class Iterator >
void sorting::non_recursive_merge_sort ( const Iterator first,
const Iterator last,
const size_t n )

bottom-up merge sort which sorts elements in a non-decreasing order

sorts elements non-recursively by breaking them into small segments, merging adjacent segments into larger sorted segments, then increasing the sizes of segments by factors of 2 and repeating the same process. best-case = worst-case = O(n log(n))

Parameters
firstpoints to the first element
lastpoints to 1-step past the last element
nthe number of elements

Definition at line 25 of file non_recursive_merge_sort.cpp.

26 {
27 // create a buffer large enough to store all elements
28 // dynamically allocated to comply with cpplint
29 char* buffer = new char[n * sizeof(*first)];
30 // buffer size can be optimized to largest power of 2 less than n
31 // elements divide the container into equally-sized segments whose
32 // length start at 1 and keeps increasing by factors of 2
33 for (size_t length(1); length < n; length <<= 1) {
34 // merge adjacent segments whose number is n / (length * 2)
35 Iterator left(first);
36 for (size_t counter(n / (length << 1)); counter; --counter) {
37 Iterator right(left + length), end(right + length);
38 merge(left, right, end, buffer);
39 left = end;
40 }
41 // if the number of remaining elements (n * 2 % length) is longer
42 // than a segment, merge the remaining elements
43 if ((n & ((length << 1) - 1)) > length)
44 merge(left, left + length, last, buffer);
45 }
46 delete[] buffer;
47}
void merge(int *arr, int l, int m, int r)

◆ non_recursive_merge_sort() [3/3]

template<class Iterator >
void sorting::non_recursive_merge_sort ( const Iterator first,
const size_t n )

bottom-up merge sort which sorts elements in a non-decreasing order

Parameters
firstpoints to the first element
nthe number of elements

Definition at line 77 of file non_recursive_merge_sort.cpp.

77 {
78 non_recursive_merge_sort(first, first + n, n);
79}

◆ partition()

int sorting::partition ( std::vector< int > & arr,
int start,
int end )

The partition function sorts the array from start to end and uses the last element as the pivot.

Parameters
arrthe array to be sorted
startstarting index
endending index
Returns
int next index of the pivot

Definition at line 33 of file quick_sort_iterative.cpp.

34{
35 int pivot = arr[end];
36 int index = start - 1;
37
38 for (int j = start; j < end; j++) {
39 if (arr[j] <= pivot) {
40 std::swap(arr[++index], arr[j]);
41 }
42 }
43
44 std::swap(arr[index + 1], arr[end]);
45 return index + 1;
46}

◆ pigeonSort()

template<std::size_t N>
std::array< int, N > sorting::pigeonSort ( std::array< int, N > arr)

Pigeonhole sorting of array of size n The function will sort the array through Pigeonhole algorithm and print

Parameters
arrunsorted array of elements
Returns
sorted array of elements

Definition at line 34 of file pigeonhole_sort.cpp.

34 {
35 // Finding min and max*
36 auto min = std::min_element(std::begin(arr), std::end(arr));
37 auto max = std::max_element(std::begin(arr), std::end(arr));
38
39 // Range refers to the number of holes required
40 int range = *max - *min + 1;
41 int *hole = new int[range]();
42
43 // Copying all array values to pigeonhole
44 for (int i = 0; i < N; i++) {
45 hole[arr[i] - *min] = arr[i];
46 }
47
48 // Deleting elements from list and storing to original array
49 int count = 0;
50 for (int i = 0; i < range; i++) {
51 while (hole[i] != '\0') {
52 arr[count] = hole[i];
53 hole[i] = {};
54 count++;
55 }
56 }
57 delete[] hole;
58
59 return arr;
60}

◆ quicksort() [1/2]

template<typename T >
void sorting::quicksort ( std::vector< T > * arr,
int32_t low,
int32_t high )

3-way partition based quick sort. This function accepts array pointer and modified the input array.

Template Parameters
Ttype of data in the vector array
Parameters
[in,out]arrvector array to sort
[in]lowlower limit of window to partition
[in]highupper limit of window to partition

Definition at line 94 of file quick_sort_3.cpp.

94 {
95 if (low >= high) { // 1 or 0 elements
96 return;
97 }
98
99 int32_t i = 0, j = 0;
100
101 // i and j are passed as reference
102 partition3(arr, low, high, &i, &j);
103
104 // Recur two halves
105 quicksort(arr, low, i);
106 quicksort(arr, j, high);
107}

◆ quicksort() [2/2]

template<typename T >
std::vector< T > sorting::quicksort ( std::vector< T > arr,
int32_t low,
int32_t high )

3-way partition based quick sort. This function accepts array by value and creates a copy of it. The array copy gets sorted and returned by the function.

Template Parameters
Ttype of data in the vector array
Parameters
[in]arrvector array to sort
[in]lowlower limit of window to partition
[in]highupper limit of window to partition
Returns
sorted array vector

Definition at line 119 of file quick_sort_3.cpp.

119 {
120 if (low >= high) { // 1 or 0 elements
121 return arr;
122 }
123
124 int32_t i = 0, j = 0;
125
126 // i and j are passed as reference
127 partition3(&arr, low, high, &i, &j);
128
129 // Recur two halves
130 quicksort(&arr, low, i);
131 quicksort(&arr, j, high);
132
133 return arr;
134}

◆ randomized_bogosort()

template<typename T , size_t N>
std::array< T, N > sorting::randomized_bogosort ( std::array< T, N > arr)

Implement randomized Bogosort algorithm and sort the elements of a given array.

Template Parameters
Ttypename of the array
Nlength of array
Parameters
arrarray to sort
Returns
new array with elements sorted from a given array

Definition at line 52 of file bogo_sort.cpp.

52 {
53 // Untill array is not sorted
54 std::random_device random_device;
55 std::mt19937 generator(random_device());
56 while (!std::is_sorted(arr.begin(), arr.end())) {
57 std::shuffle(arr.begin(), arr.end(), generator);// Shuffle the array
58 }
59 return arr;
60}

◆ recursive_bubble_sort()

template<typename T >
void sorting::recursive_bubble_sort ( std::vector< T > * nums,
uint64_t n )

This is an implementation of the recursive_bubble_sort. A vector is passed to the function which is then dereferenced, so that the changes are reflected in the original vector. It also accepts a second parameter of type int and name n, which is the size of the array.

Template Parameters
Ttype of data variables in the array
Parameters
numsour array of elements.
nsize of the array

< base case; when size of the array is 1

< iterating over the entire array

< if a larger number appears before the smaller one, swap them.

Definition at line 84 of file recursive_bubble_sort.cpp.

84 {
85 if (n == 1) {
86 return;
87 }
88
89 for (uint64_t i = 0; i < n - 1; i++) {
91 if ((*nums)[i] > (*nums)[i + 1]) {
92 std::swap((*nums)[i], (*nums)[i + 1]);
93 }
94 }
95
97 recursive_bubble_sort(nums, n - 1);
98}
void recursive_bubble_sort(std::vector< T > *nums, uint64_t n)
This is an implementation of the recursive_bubble_sort. A vector is passed to the function which is t...

◆ selectionSort()

std::vector< uint64_t > sorting::selectionSort ( const std::vector< uint64_t > & arr,
uint64_t len )

Definition at line 48 of file selection_sort_iterative.cpp.

49 {
50 std::vector<uint64_t> array(
51 arr.begin(),
52 arr.end()); // declare a vector in which result will be stored
53 for (uint64_t it = 0; it < len; ++it) {
54 uint64_t min = it; // set min value
55 for (uint64_t it2 = it + 1; it2 < len; ++it2) {
56 if (array[it2] < array[min]) { // check which element is smaller
57 min = it2; // store index of smallest element to min
58 }
59 }
60
61 if (min != it) { // swap if min does not match to i
62 uint64_t tmp = array[min];
63 array[min] = array[it];
64 array[it] = tmp;
65 }
66 }
67
68 return array; // return sorted vector
69}

◆ shell_sort() [1/3]

template<typename T >
void sorting::shell_sort ( std::vector< T > * arr)

function overload - when input array is of type std::vector, simply send the data content and the data length to the above function.

Definition at line 75 of file shell_sort2.cpp.

75 {
76 shell_sort(arr->data(), arr->size());
77}

◆ shell_sort() [2/3]

template<typename T >
void sorting::shell_sort ( T * arr,
size_t LEN )

Optimized algorithm - takes half the time by utilizing Mar

Definition at line 45 of file shell_sort2.cpp.

45 {
46 const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1};
47 const unsigned int gap_len = 8;
48 size_t i, j, g;
49
50 for (g = 0; g < gap_len; g++) {
51 unsigned int gap = gaps[g];
52 for (i = gap; i < LEN; i++) {
53 T tmp = arr[i];
54
55 for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) {
56 arr[j] = arr[j - gap];
57 }
58
59 arr[j] = tmp;
60 }
61 }
62}

◆ shell_sort() [3/3]

template<typename T , size_t N>
void sorting::shell_sort ( T(&) arr[N])

function overload - when input array is of a known length array type

Definition at line 67 of file shell_sort2.cpp.

67 {
68 shell_sort(arr, N);
69}

◆ shuffle()

template<typename T , size_t N>
std::array< T, N > sorting::shuffle ( std::array< T, N > arr)

Function to shuffle the elements of an array. (for reference)

Template Parameters
Ttypename of the array
Nlength of array
Parameters
arrarray to shuffle
Returns
new array with elements shuffled from a given array

Definition at line 37 of file bogo_sort.cpp.

37 {
38 for (int i = 0; i < N; i++) {
39 // Swaps i'th index with random index (less than array size)
40 std::swap(arr[i], arr[std::rand() % N]);
41 }
42 return arr;
43}