Skip to content

Instantly share code, notes, and snippets.

@bexp
Last active May 14, 2018 20:24
Show Gist options
  • Save bexp/022270890bebde8861a7c9c43e836dd5 to your computer and use it in GitHub Desktop.
Save bexp/022270890bebde8861a7c9c43e836dd5 to your computer and use it in GitHub Desktop.
merge sort
#include <iostream>
#include <map>
using namespace std;
void print(int *a, int num) {
for (int i = 0; i < num; i++) {
cout << " " << a[i];
}
cout << endl;
}
void merge(int* a, int left, int right) {
int mid = (left + right)/2;
int i1 = 0;
int i2 = left;
int i3 = mid +1;
int temp [right - left + 1];
cout << "merge: " << left << " " << right << endl;
while (i2 <= mid && i3 <= right) {
if (a[i2] < a[i3]) {
temp[i1++] = a[i2++];
} else {
temp[i1++] = a[i3++];
}
}
while (i2 <= mid) {
temp[i1++] = a[i2++];
}
while (i3 <= right) {
temp[i1++] = a[i3++];
}
for (int i = left; i<= right; i++ ) {
a[i] = temp[i - left];
cout << "a[" << i << "]= " << a[i] << endl;
}
}
void merge_sort(int* a, int left, int right) {
if (left < right) {
cout << "merge_sort:" << left << " " << right << endl;
int mid = (right + left)/2;
merge_sort(a, left, mid);
cout << "pass:" << left << " " << right << endl;
merge_sort(a, mid+1, right);
merge(a, left, right);
} else {
cout << "skip: " << left << " " << right << endl;
}
}
int main() {
const int num = 10;
int arr[10] = { 10, 3, 2, 5, 4, 9, 8, 6 ,7, 1 };
print(arr, num);
merge_sort(arr, 0, 3);
print(arr, num);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment