Last active
September 27, 2020 09:39
-
-
Save urbanij/2c1ad260c4bbac9de98517b564c5ed53 to your computer and use it in GitHub Desktop.
Stalin sort algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Stalin sort algorithm | |
* @urbanij | |
* g++ -std=c++98 stalin_sort.cpp -o stalin_sort | |
*/ | |
#include <iostream> | |
#include <time.h> | |
#define N 30 | |
void populate_array(int* arr, int n) { | |
srand (time(NULL)); | |
for (int i=0; i<n; ++i) { | |
arr[i] = rand() % 100; | |
} | |
} | |
void print(int* arr, int n) { | |
for (int i=0; i<n; ++i) { | |
if (arr[i] == -1) break; | |
std::cout << arr[i] << ' '; | |
} | |
std::cout << '\n'; | |
} | |
void stalin_sort(int* sorted_arr, int* arr, int n) { | |
int last_elem = arr[0]; | |
sorted_arr[0] = last_elem; | |
int index_sorted_arr = 1; | |
for (int i=1; i<n; ++i) { | |
if (arr[i] >= last_elem) { | |
sorted_arr[index_sorted_arr++] = arr[i]; | |
last_elem = arr[i]; | |
} | |
} | |
} | |
int main() { | |
std::cout << "Stalin sort algorithm:\n\n\teach element that is not in the\n\tcorrect order is simply eliminated from the list.\n\n"; | |
int arr[N], sorted_arr[N]; | |
memset(sorted_arr, -1, sizeof sorted_arr); | |
populate_array(arr, N); | |
stalin_sort(sorted_arr, arr, N); | |
print(arr, N); | |
print(sorted_arr, N); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment