Created
May 3, 2023 21:33
-
-
Save maxgoren/5f327e525aa1d4185c0fb63da93ab762 to your computer and use it in GitHub Desktop.
A very naiive mergesort
This file contains hidden or 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
/* | |
This highlights the problems with big O notation. This algorithm is | |
a naiive mergesort implementation. When analyzed its clear to see it is O(nlogn) | |
however, this implementation takesd over 5 seconds to sort 2.5m int's where | |
a well done implementation can do it in 1/10th the time. | |
*/ | |
vector<int> merge(vector<int>& a, vector<int>& b) { | |
int i = 0, j = 0; | |
vector<int> res; | |
while (i < a.size() && j < b.size()) { | |
if (a[i] < b[j]) { | |
res.push_back(a[i++]); | |
} else { | |
res.push_back(b[j++]); | |
} | |
} | |
while (i < a.size()) res.push_back(a[i++]); | |
while (j < b.size()) res.push_back(b[j++]); | |
return res; | |
} | |
void mergesort(vector<int>& in) { | |
if (in.size() <= 1) | |
return; | |
vector<int> front, back; | |
int m = in.size() / 2; | |
for (int i = 0; i < in.size(); i++) { | |
if (i < m) front.push_back(in[i]); | |
else back.push_back(in[i]); | |
} | |
mergesort(front); | |
mergesort(back); | |
in = merge(front, back); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment