Last active
December 14, 2015 20:19
-
-
Save emrahgunduz/5143535 to your computer and use it in GitHub Desktop.
Changed the input style
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
/* | |
* File: main.cpp | |
* Author: emrahgunduz | |
* | |
* Created on March 12, 2013, 3:57 PM | |
*/ | |
#include <iostream> | |
using namespace std; | |
void merge(int*, int*, int, int, int); | |
void mergesort(int *a, int*b, int start, int end) { | |
int halfpoint; | |
if (start < end) { | |
halfpoint = (start + end) / 2; | |
mergesort(a, b, start, halfpoint); | |
mergesort(a, b, halfpoint + 1, end); | |
merge(a, b, start, halfpoint, end); | |
} | |
} | |
void merge(int *a, int *b, int start, int halfpoint, int end) { | |
int h, i, j, k; | |
h = start; | |
i = start; | |
j = halfpoint + 1; | |
while ((h <= halfpoint) && (j <= end)) { | |
if (a[h] <= a[j]) { | |
b[i] = a[h]; | |
h++; | |
} else { | |
b[i] = a[j]; | |
j++; | |
} | |
i++; | |
} | |
if (h > halfpoint) { | |
for (k = j; k <= end; k++) { | |
b[i] = a[k]; | |
i++; | |
} | |
} else { | |
for (k = h; k <= halfpoint; k++) { | |
b[i] = a[k]; | |
i++; | |
} | |
} | |
// Write the final sorted array to our original one | |
for (k = start; k <= end; k++) { | |
a[k] = b[k]; | |
} | |
} | |
int main(int argc, char** argv) { | |
int num; | |
cout << "How many numbers do you want to sort: "; | |
cin >> num; | |
int a[num]; | |
int b[num]; | |
for (int i = 0; i < num; i++) { | |
cout << (i + 1) << ": "; | |
cin >> a[i]; | |
} | |
// Start merge sort | |
mergesort(a, b, 0, num - 1); | |
// Print the sorted array | |
cout << endl; | |
for (int i = 0; i < num; i++) { | |
cout << a[i] << " "; | |
} | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment