From 6584f8491b4f8fb6ad8e6a9278b80090d1218827 Mon Sep 17 00:00:00 2001 From: Koo Xin Tong Date: Mon, 8 Aug 2022 15:18:24 +0800 Subject: [PATCH] (C++) add bead sort into sorting algorithm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The algorithm’s run–time complexity ranges from O(n) to O(S) --- .gitignore | 9 ++++ algorithms/CPlusPlus/README.md | 1 + algorithms/CPlusPlus/Sorting/bead-sort.cpp | 56 ++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 algorithms/CPlusPlus/Sorting/bead-sort.cpp diff --git a/.gitignore b/.gitignore index c15b5c75..656b63b7 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,12 @@ Thumbs.db # Visual Studio Code .vscode/ +.vs/DSA/v16/.suo +.vs/DSA/v16/Browse.VC.db +.vs/DSA/v16/Browse.VC.db-shm +.vs/DSA/v16/Browse.VC.db-wal +.vs/DSA/v16/Browse.VC.opendb +.vs/ProjectSettings.json +.vs/slnx.sqlite +.vs/DSA/v16/ipch/AutoPCH/26ffe219c79f338e/BEAD-SORT.ipch +.vs/VSWorkspaceState.json diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index c545fa88..83e30455 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -109,6 +109,7 @@ - [Merge Sort](Sorting/merge-sort.cpp) - [Wave Sort](Sorting/wave-sort.cpp) - [Cycle Sort](Sorting/cycle-sort.cpp) +- [Bead Sort](Sorting/bead-sort.cpp) ## Strings diff --git a/algorithms/CPlusPlus/Sorting/bead-sort.cpp b/algorithms/CPlusPlus/Sorting/bead-sort.cpp new file mode 100644 index 00000000..24dfa761 --- /dev/null +++ b/algorithms/CPlusPlus/Sorting/bead-sort.cpp @@ -0,0 +1,56 @@ +// C++ program to implement gravity/bead sort +#include +#include + +#define BEAD(i, j) beads[i * max + j] + +// function to perform the above algorithm +void beadSort(int* a, int len) { + // Find the maximum element + int max = a[0]; + for (int i = 1; i < len; i++) + if (a[i] > max) + max = a[i]; + + // allocating memory + unsigned char* beads = new unsigned char[max * len]; + memset(beads, 0, static_cast(max) * len); + + // mark the beads + for (int i = 0; i < len; i++) + for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; + + for (int j = 0; j < max; j++) { + // count how many beads are on each post + int sum = 0; + for (int i = 0; i < len; i++) { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + + // Move beads down + for (int i = len - sum; i < len; i++) BEAD(i, j) = 1; + } + + // Put sorted values in array using beads + for (int i = 0; i < len; i++) { + int j; + for (j = 0; j < max && BEAD(i, j); j++) { + } + + a[i] = j; + } + delete[] beads; +} + +// driver function to test the algorithm +int main() { + int a[] = { 5, 3, 1, 7, 4, 1, 1, 20 }; + int len = sizeof(a) / sizeof(a[0]); + + beadSort(a, len); + + for (int i = 0; i < len; i++) printf("%d ", a[i]); + + return 0; +} \ No newline at end of file