Skip to content

Commit

Permalink
Add thanos sort in cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
ricglz authored and OtacilioN committed Oct 4, 2019
1 parent e49c75d commit 046b12e
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions ThanosSort/thanos_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>

using namespace std;

// Time complexity: O(n)
vector<int> randomUniverse() {
vector<int> universe;
srand(time(NULL));
for(int i = 0; i < 100; i++) {
universe.push_back(rand() % 1000);
}
return universe;
}

// Time complexity: O(n)
void printUniverse(string universeName, vector<int> universe) {
int universeSize = universe.size();
cout << universeName << ": [" << universe[0];
for(int i = 1; i < universeSize; i++) {
cout << ", " << universe[i];
}
cout << "]" << endl;
}

// Time complexity: O(n)
bool isSorted(vector<int> array) {
int size = array.size();
for(int i = 1; i < size; i++) {
if(array[i - 1] > array[i]) {
return false;
}
}
return true;
}

// Time complexity: O(n)
void killRandomElement(vector<int>& universe) {
int index = rand() % universe.size();
universe.erase(universe.begin() + index);
}

// Time complexity: O(n ^ 2)
void killHalfUniverse(vector<int>& universe) {
int halfUniverseSize = universe.size() / 2;
for(int i = 0; i < halfUniverseSize; i++) {
killRandomElement(universe);
}
}

// Time complexity: O(n ^ 2 * log n)
void thanosSort(vector<int>& universe) {
while(!isSorted(universe)) {
killHalfUniverse(universe);
}
}

// Time complexity: O(n ^ 2 * log n)
int main() {
vector<int> universe = randomUniverse();
printUniverse("Universe", universe);
thanosSort(universe);
printUniverse("Ordered universe: ", universe);
return 0;
}

0 comments on commit 046b12e

Please sign in to comment.