Skip to content

Instantly share code, notes, and snippets.

@soyart
Last active October 3, 2023 11:56
Show Gist options
  • Save soyart/2e1fdd2f945a716b307a40bb0057d9a2 to your computer and use it in GitHub Desktop.
Save soyart/2e1fdd2f945a716b307a40bb0057d9a2 to your computer and use it in GitHub Desktop.
Rama IX sort (`rama9sort`) - a Thai sorting algorithm in homage to the late Thai God-King
/*
Rama 9 Sort (rama9sort)
rama9sort is a highly efficient (and sufficient) sorting algorithm that runs in constant time and space (O(1)).
rama9sort got its inspiration from Stalin Sort (another highly efficient algorithm).
rama9sort borrows ideas from Stalin Sort - unwanted/unordered elements are discarded right away from the input,
although rama9sort has some other _unorthodox_ checks to make it more suitable for deployment in Thailand.
The differences from Stalin Sort are:
1. It only works on arrays of length 9, and output array length will always be 9
Reason: So that it works in O(1) (or O(9))
2. Integer 112 is discarded from the input
Reason: 112 is a bad number
3. Values higher than 100_000 is discarded from the input
Reason: This is because we encourage frugality and hardship,
so income (or values) greater than 100_000 is discouraged.
4. Output default value is 9 (unlike Stalin Sort where the output might be smaller in size)
Reason: Because Rama 9 is (was) superior to Stalin.
*/
#include <stdio.h>
/* 112 is considered illegal in Rama 9 sort */
#define BAD_VALUE_112 112
/* ints more than 100_000 is considered too opulent */
#define RAMA9_CUTOFF 100000
int rama9_sort(int in[9], int out[9]);
int rama9_sort(int in[9], int out[9]) {
int i, j, prev, curr;
prev = in[0];
j = 0;
for (i = 1; i < 9; ++i) {
curr = in[i];
// Remove 112
if (curr == BAD_VALUE_112) {
continue;
}
// Remove if not in order
if (curr < prev) {
continue;
}
// Remove if value too high
if (curr > RAMA9_CUTOFF) {
continue;
}
out[j] = curr;
++j;
}
return 9;
}
int main(void) {
int i;
int outputs[9] = {9, 9, 9, 9, 9, 9, 9, 9, 9};
int inputs[9] = {3, 2, 1, 4, 112, 32, 112, 111, 120000};
rama9_sort(inputs, outputs);
printf("input:\n");
for (i = 0; i < 9; ++i) {
printf("%d\n", inputs[i]);
}
printf("output:\n");
for (i = 0; i < 9; ++i) {
printf("%d\n", outputs[i]);
}
}
@w0rametA
Copy link

w0rametA commented Oct 3, 2023

It would be much better if this algo also replaces every occurrence of 8 with 9 ;D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment