Skip to content

Commit 7a41a30

Browse files
committed
chore:flash-sort
1 parent ba0d3ff commit 7a41a30

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

sorting/flash_sort.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* @file
3+
* @brief Implementation of the Flash Sort algorithm.
4+
* @details
5+
* Flash Sort is an in-place, linear-time sorting algorithm for uniformly distributed data.
6+
* It divides the data into classes, rearranges elements into their respective classes,
7+
* and then sorts each class using insertion sort.
8+
* @see https://en.wikipedia.org/wiki/Flashsort
9+
* @note Flash Sort is not a stable sorting algorithm.
10+
* @author [Sachin Pangal](https://github.com/orthodox-64)
11+
*/
12+
13+
#include <iostream>
14+
#include <vector>
15+
#include <algorithm>
16+
17+
/**
18+
* @brief Sorts an array using the Flash Sort algorithm.
19+
* @param arr The array to be sorted.
20+
* @param n The number of elements in the array.
21+
*/
22+
23+
void flashSort(std::vector<float>& arr) {
24+
int n = arr.size();
25+
if (n <= 1) return;
26+
27+
// Step 1: Find the minimum and maximum values in the array
28+
float minVal = *std::min_element(arr.begin(), arr.end());
29+
float maxVal = *std::max_element(arr.begin(), arr.end());
30+
31+
// Step 2: Calculate the number of classes (buckets)
32+
int numClasses = 0.45 * n;
33+
if (numClasses < 2) numClasses = 2;
34+
35+
// Step 3: Create a histogram of the data
36+
std::vector<int> count(numClasses, 0);
37+
for (int i = 0; i < n; ++i) {
38+
int index = numClasses * (arr[i] - minVal) / (maxVal - minVal);
39+
count[index]++;
40+
}
41+
42+
// Step 4: Calculate the starting index of each class
43+
std::vector<int> pos(numClasses, 0);
44+
pos[0] = 0;
45+
for (int i = 1; i < numClasses; ++i) {
46+
pos[i] = pos[i - 1] + count[i - 1];
47+
}
48+
49+
// Step 5: Rearrange the array into classes
50+
std::vector<float> temp = arr;
51+
for (int i = 0; i < n; ++i) {
52+
int index = numClasses * (arr[i] - minVal) / (maxVal - minVal);
53+
arr[pos[index]++] = temp[i];
54+
}
55+
56+
// Step 6: Sort each class using insertion sort
57+
for (int i = 0; i < numClasses; ++i) {
58+
int start = pos[i] - count[i];
59+
int end = pos[i];
60+
std::sort(arr.begin() + start, arr.begin() + end);
61+
}
62+
}
63+
64+
// Driver code to test the Flash Sort
65+
int main() {
66+
std::vector<float> arr = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
67+
flashSort(arr);
68+
69+
std::cout << "Sorted array is: ";
70+
for (float num : arr) {
71+
std::cout << num << " ";
72+
}
73+
return 0;
74+
}

0 commit comments

Comments
 (0)