Created
September 18, 2013 20:42
-
-
Save nazywamsiepawel/6615365 to your computer and use it in GitHub Desktop.
merge sort using stl queues
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
#include <iostream> | |
#include <queue> | |
using namespace std; | |
void merge(int s[], int low, int middle, int high){ | |
int i; | |
queue<int> buffer1, buffer2; | |
for(i=low; i<=middle; i++) buffer1.push(s[i]); | |
for(i=middle+1; i<=high; i++) buffer2.push(s[i]); | |
i = low; | |
while(buffer1.size() && buffer2.size()){ | |
int temp1, temp2; | |
temp1 = buffer1.front(); | |
temp2 = buffer2.front(); | |
if(temp1<=temp2){ | |
buffer1.pop(); | |
s[i++] = temp1; | |
} else { | |
buffer2.pop(); | |
s[i++] = temp2; | |
} | |
} | |
while(buffer1.size()){ | |
s[i++] = buffer1.front(); | |
buffer1.pop(); | |
} | |
while(buffer2.size()){ | |
s[i++] = buffer2.front(); | |
buffer2.pop(); | |
} | |
} | |
void mergesort(int s[], int low, int high){ | |
int middle; | |
if(low < high){ | |
middle = (low+high)/2; | |
mergesort(s, low, middle); | |
mergesort(s, middle+1, high); | |
merge(s, low, middle, high); | |
} | |
} | |
int main(){ | |
int n, i; | |
int numbers[] = {5, 4, 2, 6, 7, 5, 3, 78, 34, 1, 4, 32}; | |
mergesort(numbers, 0, sizeof(numbers)/sizeof(int)-1); | |
for(int j = 0; j<sizeof(numbers)/sizeof(int); j++) | |
cout<<numbers[j]<<endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment