Merge remote-tracking branch 'upstream/master' into quick_sort

This commit is contained in:
Krishna Vedala
2020-07-18 17:31:02 -04:00
58 changed files with 4161 additions and 709 deletions

View File

@@ -14,7 +14,7 @@ void beadSort(int *a, int len) {
// allocating memory
unsigned char *beads = new unsigned char[max * len];
memset(beads, 0, max * len);
memset(beads, 0, static_cast<size_t>(max) * len);
// mark the beads
for (int i = 0; i < len; i++)

115
sorting/bogo_sort.cpp Normal file
View File

@@ -0,0 +1,115 @@
/**
* @file
* @brief Implementation of [Bogosort algorithm](https://en.wikipedia.org/wiki/Bogosort)
*
* @details
* In computer science, bogosort (also known as permutation sort, stupid sort, slowsort,
* shotgun sort, random sort, monkey sort, bobosort or shuffle sort) is a highly inefficient
* sorting algorithm based on the generate and test paradigm. Two versions of this algorithm
* exist: a deterministic version that enumerates all permutations until it hits a sorted one,
* and a randomized version that randomly permutes its input.Randomized version is implemented here.
*
* Algorithm -
*
* Shuffle the array untill array is sorted.
*
*/
#include <iostream>
#include <algorithm>
#include <array>
#include <cassert>
/**
* @namespace sorting
* @brief Sorting algorithms
*/
namespace sorting {
/**
* Function to shuffle the elements of an array. (for reference)
* @tparam T typename of the array
* @tparam N length of array
* @param arr array to shuffle
* @returns new array with elements shuffled from a given array
*/
template <typename T, size_t N>
std::array <T, N> shuffle (std::array <T, N> arr) {
for (int i = 0; i < N; i++) {
// Swaps i'th index with random index (less than array size)
std::swap(arr[i], arr[std::rand() % N]);
}
return arr;
}
/**
* Implement randomized Bogosort algorithm and sort the elements of a given array.
* @tparam T typename of the array
* @tparam N length of array
* @param arr array to sort
* @returns new array with elements sorted from a given array
*/
template <typename T, size_t N>
std::array <T, N> randomized_bogosort (std::array <T, N> arr) {
// Untill array is not sorted
while (!std::is_sorted(arr.begin(), arr.end())) {
std::random_shuffle(arr.begin(), arr.end());// Shuffle the array
}
return arr;
}
} // namespace sorting
/**
* Function to display array on screen
* @tparam T typename of the array
* @tparam N length of array
* @param arr array to display
*/
template <typename T, size_t N>
void show_array (const std::array <T, N> &arr) {
for (int x : arr) {
std::cout << x << ' ';
}
std::cout << '\n';
}
/**
* Function to test above algorithm
*/
void test() {
// Test 1
std::array <int, 5> arr1;
for (int &x : arr1) {
x = std::rand() % 100;
}
std::cout << "Original Array : ";
show_array(arr1);
arr1 = sorting::randomized_bogosort(arr1);
std::cout << "Sorted Array : ";
show_array(arr1);
assert(std::is_sorted(arr1.begin(), arr1.end()));
// Test 2
std::array <int, 5> arr2;
for (int &x : arr2) {
x = std::rand() % 100;
}
std::cout << "Original Array : ";
show_array(arr2);
arr2 = sorting::randomized_bogosort(arr2);
std::cout << "Sorted Array : ";
show_array(arr2);
assert(std::is_sorted(arr2.begin(), arr2.end()));
}
/** Driver Code */
int main() {
// Testing
test();
// Example Usage
std::array <int, 5> arr = {3, 7, 10, 4, 1}; // Defining array which we want to sort
std::cout << "Original Array : ";
show_array(arr);
arr = sorting::randomized_bogosort(arr); // Callling bogo sort on it
std::cout << "Sorted Array : ";
show_array(arr); // Printing sorted array
return 0;
}

View File

@@ -1,49 +1,101 @@
// Kind of better version of Bubble sort.
// While Bubble sort is comparering adjacent value, Combsort is using gap larger
// than 1 Best case: O(n) Worst case: O(n ^ 2)
/**
*
* \file
* \brief [Comb Sort Algorithm
* (Comb Sort)](https://en.wikipedia.org/wiki/Comb_sort)
*
* \author
*
* \details
* - A better version of bubble sort algorithm
* - Bubble sort compares adjacent values whereas comb sort uses gap larger
* than 1
* - Best case Time complexity O(n)
* Worst case Time complexity O(n^2)
*
*/
#include <algorithm>
#include <cassert>
#include <iostream>
int a[100005];
int n;
/**
*
* Find the next gap by shrinking the current gap by shrink factor of 1.3
* @param gap current gap
* @return new gap
*
*/
int FindNextGap(int gap) {
gap = (gap * 10) / 13;
int FindNextGap(int x) {
x = (x * 10) / 13;
return std::max(1, x);
return std::max(1, gap);
}
void CombSort(int a[], int l, int r) {
// Init gap
int gap = n;
/** Function to sort array
*
* @param arr array to be sorted
* @param l start index of array
* @param r end index of array
*
*/
void CombSort(int *arr, int l, int r) {
/**
*
* initial gap will be maximum and the maximum possible value is
* the size of the array that is n and which is equal to r in this
* case so to avoid passing an extra parameter n that is the size of
* the array we are using r to initialize the initial gap.
*
*/
int gap = r;
// Initialize swapped as true to make sure that loop runs
/// Initialize swapped as true to make sure that loop runs
bool swapped = true;
// Keep running until gap = 1 or none elements were swapped
/// Keep running until gap = 1 or none elements were swapped
while (gap != 1 || swapped) {
// Find next gap
/// Find next gap
gap = FindNextGap(gap);
swapped = false;
// Compare all elements with current gap
/// Compare all elements with current gap
for (int i = l; i <= r - gap; ++i) {
if (a[i] > a[i + gap]) {
std::swap(a[i], a[i + gap]);
if (arr[i] > arr[i + gap]) {
std::swap(arr[i], arr[i + gap]);
swapped = true;
}
}
}
}
void tests() {
/// Test 1
int arr1[10] = {34, 56, 6, 23, 76, 34, 76, 343, 4, 76};
CombSort(arr1, 0, 10);
assert(std::is_sorted(arr1, arr1 + 10));
std::cout << "Test 1 passed\n";
/// Test 2
int arr2[8] = {-6, 56, -45, 56, 0, -1, 8, 8};
CombSort(arr2, 0, 8);
assert(std::is_sorted(arr2, arr2 + 8));
std::cout << "Test 2 Passed\n";
}
/** Main function */
int main() {
/// Running predefined tests
tests();
/// For user interaction
int n;
std::cin >> n;
for (int i = 1; i <= n; ++i) std::cin >> a[i];
CombSort(a, 1, n);
for (int i = 1; i <= n; ++i) std::cout << a[i] << ' ';
int *arr = new int[n];
for (int i = 0; i < n; ++i) std::cin >> arr[i];
CombSort(arr, 0, n);
for (int i = 0; i < n; ++i) std::cout << arr[i] << ' ';
delete[] arr;
return 0;
}

133
sorting/gnome_sort.cpp Normal file
View File

@@ -0,0 +1,133 @@
/**
* @file
* @brief Implementation of [gnome
* sort](https://en.wikipedia.org/wiki/Gnome_sort) algorithm.
* @author [beqakd](https://github.com/beqakd)
* @author [Krishna Vedala](https://github.com/kvedala)
* @details
* Gnome sort algorithm is not the best one but it is widely used.
* The algorithm iteratively checks the order of pairs in the array. If they are
* on right order it moves to the next successive pair, otherwise it swaps
* elements. This operation is repeated until no more swaps are made thus
* indicating the values to be in ascending order.
*
* The time Complexity of the algorithm is \f$O(n^2)\f$ and in some cases it
* can be \f$O(n)\f$.
*/
#include <algorithm> // for std::swap
#include <array> // for std::array
#include <cassert> // for assertions
#include <iostream> // for io operations
/**
* @namespace sorting
* Sorting algorithms
*/
namespace sorting {
/**
* This implementation is for a C-style array input that gets modified in place.
* @param [in,out] arr our array of elements.
* @param size size of given array
*/
template <typename T>
void gnomeSort(T *arr, int size) {
// few easy cases
if (size <= 1) {
return;
}
int index = 0; // initialize some variables.
while (index < size) {
// check for swap
if ((index == 0) || (arr[index] >= arr[index - 1])) {
index++;
} else {
std::swap(arr[index], arr[index - 1]); // swap
index--;
}
}
}
/**
* 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.
* @tparam T type of data variables in the array
* @tparam size size of the array
* @param [in] arr our array of elements.
* @return array with elements sorted
*/
template <typename T, size_t size>
std::array<T, size> gnomeSort(std::array<T, size> arr) {
// few easy cases
if (size <= 1) {
return arr;
}
int index = 0; // initialize loop index
while (index < size) {
// check for swap
if ((index == 0) || (arr[index] >= arr[index - 1])) {
index++;
} else {
std::swap(arr[index], arr[index - 1]); // swap
index--;
}
}
return arr;
}
} // namespace sorting
/**
* Test function
*/
static void test() {
// Example 1. Creating array of int,
std::cout << "Test 1 - as a C-array...";
const int size = 6;
std::array<int, size> arr = {-22, 100, 150, 35, -10, 99};
sorting::gnomeSort(arr.data(),
size); // pass array data as a C-style array pointer
assert(std::is_sorted(std::begin(arr), std::end(arr)));
std::cout << " Passed\n";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << ", ";
}
std::cout << std::endl;
// Example 2. Creating array of doubles.
std::cout << "\nTest 2 - as a std::array...";
std::array<double, size> double_arr = {-100.2, 10.2, 20.0, 9.0, 7.5, 7.2};
std::array<double, size> sorted_arr = sorting::gnomeSort(double_arr);
assert(std::is_sorted(std::begin(sorted_arr), std::end(sorted_arr)));
std::cout << " Passed\n";
for (int i = 0; i < size; i++) {
std::cout << double_arr[i] << ", ";
}
std::cout << std::endl;
// Example 3. Creating random array of float.
std::cout << "\nTest 3 - 200 random numbers as a std::array...";
const int size2 = 200;
std::array<float, size2> rand_arr{};
for (auto &a : rand_arr) {
// generate random numbers between -5.0 and 4.99
a = float(std::rand() % 1000 - 500) / 100.f;
}
std::array<float, size2> float_arr = sorting::gnomeSort(rand_arr);
assert(std::is_sorted(std::begin(float_arr), std::end(float_arr)));
std::cout << " Passed\n";
// for (int i = 0; i < size; i++) std::cout << double_arr[i] << ", ";
std::cout << std::endl;
}
/**
* Our main function with example of sort method.
*/
int main() {
test();
return 0;
}

View File

@@ -1,52 +1,123 @@
/**
* \file
* \brief [Heap Sort Algorithm
* (heap sort)](https://en.wikipedia.org/wiki/Heapsort) implementation
*
* \author [Ayaan Khan](http://github.com/ayaankhan98)
*
* \details
* Heap-sort is a comparison-based sorting algorithm.
* Heap-sort can be thought of as an improved selection sort:
* like selection sort, heap sort divides its input into a sorted
* and an unsorted region, and it iteratively shrinks the unsorted
* region by extracting the largest element from it and inserting
* it into the sorted region. Unlike selection sort,
* heap sort does not waste time with a linear-time scan of the
* unsorted region; rather, heap sort maintains the unsorted region
* in a heap data structure to more quickly find the largest element
* in each step.
*
* Time Complexity - \f$O(n \log(n))\f$
*
*/
#include <algorithm>
#include <cassert>
#include <iostream>
void heapify(int *a, int i, int n) {
int largest = i;
const int l = 2 * i + 1;
const int r = 2 * i + 2;
/**
*
* Utility function to print the array after
* sorting.
*
* @param arr array to be printed
* @param sz size of array
*
*/
template <typename T>
void printArray(T *arr, int sz) {
for (int i = 0; i < sz; i++) std::cout << arr[i] << " ";
std::cout << "\n";
}
if (l < n && a[l] > a[largest])
/**
*
* \addtogroup sorting Sorting Algorithm
* @{
*
* The heapify procedure can be thought of as building a heap from
* the bottom up by successively sifting downward to establish the
* heap property.
*
* @param arr array to be sorted
* @param n size of array
* @param i node position in Binary Tress or element position in
* Array to be compared with it's childern
*
*/
template <typename T>
void heapify(T *arr, int n, int i) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && a[r] > a[largest])
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
std::swap(a[i], a[largest]);
heapify(a, n, largest);
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapsort(int *a, int n) {
for (int i = n - 1; i >= 0; --i) {
std::swap(a[0], a[i]);
heapify(a, 0, i);
/**
* Utilizes heapify procedure to sort
* the array
*
* @param arr array to be sorted
* @param n size of array
*
*/
template <typename T>
void heapSort(T *arr, int n) {
for (int i = n - 1; i >= 0; i--) heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
std::swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
void build_maxheap(int *a, int n) {
for (int i = n / 2 - 1; i >= 0; --i) {
heapify(a, i, n);
}
/**
*
* @}
* Test cases to test the program
*
*/
void test() {
std::cout << "Test 1\n";
int arr[] = {-10, 78, -1, -6, 7, 4, 94, 5, 99, 0};
int sz = sizeof(arr) / sizeof(arr[0]); // sz - size of array
printArray(arr, sz); // displaying the array before sorting
heapSort(arr, sz); // calling heapsort to sort the array
printArray(arr, sz); // display array after sorting
assert(std::is_sorted(arr, arr + sz));
std::cout << "Test 1 Passed\n========================\n";
std::cout << "Test 2\n";
double arr2[] = {4.5, -3.6, 7.6, 0, 12.9};
sz = sizeof(arr2) / sizeof(arr2[0]);
printArray(arr2, sz);
heapSort(arr2, sz);
printArray(arr2, sz);
assert(std::is_sorted(arr2, arr2 + sz));
std::cout << "Test 2 passed\n";
}
/** Main function */
int main() {
int n;
std::cout << "Enter number of elements of array\n";
std::cin >> n;
int a[20];
for (int i = 0; i < n; ++i) {
std::cout << "Enter Element " << i << std::endl;
std::cin >> a[i];
}
build_maxheap(a, n);
heapsort(a, n);
std::cout << "Sorted Output\n";
for (int i = 0; i < n; ++i) {
std::cout << a[i] << std::endl;
}
std::getchar();
test();
return 0;
}

View File

@@ -1,36 +1,179 @@
// Insertion Sort
/**
*
* \file
* \brief [Insertion Sort Algorithm
* (Insertion Sort)](https://en.wikipedia.org/wiki/Insertion_sort)
*
* \details
* Insertion sort is a simple sorting algorithm that builds the final
* sorted array one at a time. It is much less efficient compared to
* other sorting algorithms like heap sort, merge sort or quick sort.
* However it has several advantages such as
* 1. Easy to implement
* 2. For small set of data it is quite efficient
* 3. More efficient that other Quadratic complexity algorithms like
* Selection sort or bubble sort.
* 4. It's stable that is it does not change the relative order of
* elements with equal keys
* 5. Works on hand means it can sort the array or list as it receives.
*
* It is based on the same idea that people use to sort the playing cards in
* their hands.
* the algorithms goes in the manner that we start iterating over the array
* of elements as soon as we find a unsorted element that is a misplaced
* element we place it at a sorted position.
*
* Example execution steps:
* 1. Suppose initially we have
* \f{bmatrix}{4 &3 &2 &5 &1\f}
* 2. We start traversing from 4 till we reach 1
* when we reach at 3 we find that it is misplaced so we take 3 and place
* it at a correct position thus the array will become
* \f{bmatrix}{3 &4 &2 &5 &1\f}
* 3. In the next iteration we are at 2 we find that this is also misplaced so
* we place it at the correct sorted position thus the array in this iteration
* becomes
* \f{bmatrix}{2 &3 &4 &5 &1\f}
* 4. We do not do anything with 5 and move on to the next iteration and
* select 1 which is misplaced and place it at correct position. Thus, we have
* \f{bmatrix}{1 &2 &3 &4 &5\f}
*/
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
int main() {
int n;
std::cout << "\nEnter the length of your array : ";
std::cin >> n;
int *Array = new int[n];
std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : ";
// Input
for (int i = 0; i < n; i++) {
std::cin >> Array[i];
}
// Sorting
/** \namespace sorting
* \brief Sorting algorithms
*/
namespace sorting {
/** \brief
* Insertion Sort Function
*
* @tparam T type of array
* @param [in,out] arr Array to be sorted
* @param n Size of Array
*/
template <typename T>
void insertionSort(T *arr, int n) {
for (int i = 1; i < n; i++) {
int temp = Array[i];
T temp = arr[i];
int j = i - 1;
while (j >= 0 && temp < Array[j]) {
Array[j + 1] = Array[j];
while (j >= 0 && temp < arr[j]) {
arr[j + 1] = arr[j];
j--;
}
Array[j + 1] = temp;
arr[j + 1] = temp;
}
}
/** Insertion Sort Function
*
* @tparam T type of array
* @param [in,out] arr pointer to array to be sorted
*/
template <typename T>
void insertionSort(std::vector<T> *arr) {
size_t n = arr->size();
for (size_t i = 1; i < n; i++) {
T temp = arr[0][i];
int32_t j = i - 1;
while (j >= 0 && temp < arr[0][j]) {
arr[0][j + 1] = arr[0][j];
j--;
}
arr[0][j + 1] = temp;
}
}
} // namespace sorting
/**
* @brief Create a random array objecthelper function to create a random array
*
* @tparam T type of array
* @param arr array to fill (must be pre-allocated)
* @param N number of array elements
*/
template <typename T>
static void create_random_array(T *arr, int N) {
while (N--) {
double r = (std::rand() % 10000 - 5000) / 100.f;
arr[N] = static_cast<T>(r);
}
}
/** Test Cases to test algorithm */
void tests() {
int arr1[10] = {78, 34, 35, 6, 34, 56, 3, 56, 2, 4};
std::cout << "Test 1... ";
sorting::insertionSort(arr1, 10);
assert(std::is_sorted(arr1, arr1 + 10));
std::cout << "passed" << std::endl;
int arr2[5] = {5, -3, 7, -2, 1};
std::cout << "Test 2... ";
sorting::insertionSort(arr2, 5);
assert(std::is_sorted(arr2, arr2 + 5));
std::cout << "passed" << std::endl;
float arr3[5] = {5.6, -3.1, -3.0, -2.1, 1.8};
std::cout << "Test 3... ";
sorting::insertionSort(arr3, 5);
assert(std::is_sorted(arr3, arr3 + 5));
std::cout << "passed" << std::endl;
std::vector<float> arr4({5.6, -3.1, -3.0, -2.1, 1.8});
std::cout << "Test 4... ";
sorting::insertionSort(&arr4);
assert(std::is_sorted(std::begin(arr4), std::end(arr4)));
std::cout << "passed" << std::endl;
int arr5[50];
std::cout << "Test 5... ";
create_random_array(arr5, 50);
sorting::insertionSort(arr5, 50);
assert(std::is_sorted(arr5, arr5 + 50));
std::cout << "passed" << std::endl;
float arr6[50];
std::cout << "Test 6... ";
create_random_array(arr6, 50);
sorting::insertionSort(arr6, 50);
assert(std::is_sorted(arr6, arr6 + 50));
std::cout << "passed" << std::endl;
}
/** Main Function */
int main() {
/// Running predefined tests to test algorithm
tests();
/// For user insteraction
size_t n;
std::cout << "Enter the length of your array (0 to exit): ";
std::cin >> n;
if (n == 0) {
return 0;
}
// Output
int *arr = new int[n];
std::cout << "Enter any " << n << " Numbers for Unsorted Array : ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
sorting::insertionSort(arr, n);
std::cout << "\nSorted Array : ";
for (int i = 0; i < n; i++) {
std::cout << Array[i] << "\t";
std::cout << arr[i] << " ";
}
delete[] Array;
std::cout << std::endl;
delete[] arr;
return 0;
}