1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
// tester.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void merge(int *left, int l, int *right, int r, int *arr, int a) {
int left_pos, right_pos, arr_pos;
left_pos = right_pos = arr_pos =0;
while((left_pos < l) && (right_pos < r)) {
if (left[left_pos] <= right[right_pos]) {
arr[arr_pos] = left[left_pos];
left_pos++;
}
else {
arr[arr_pos] = right[right_pos];
right_pos++;
}
arr_pos++;
}
while(left_pos < l) {
arr[arr_pos] = left[left_pos];
left_pos++;
arr_pos++;
}
while(right_pos < r) {
arr[arr_pos] = right[right_pos];
right_pos++;
arr_pos++;
}
}
void mergesort(int *a, int size) {
int* left = NULL;
int* right = NULL;
if(size > 1) {
int mid = size/2;
left = new int[mid];
right = new int[size-mid];
right[size-mid] = a[size];
for(int x = 0; x < mid; x++) {
left[x] = a[x];
right[x] = a[mid+x];
}
mergesort(left, mid);
mergesort(right, size-mid);
merge(left, mid, right, size-mid, a, size);
delete [] left;
delete [] right;
left = NULL;
right = NULL;
}
}
int _tmain(int argc, _TCHAR* argv[]) {
int arr[10] = {536, 34, 5, 6, 3, 42, 24, 42, 5, 245};
int size = sizeof(arr)/sizeof(int);
mergesort(arr, size);
for(int x = 0; x < sizeof(arr)/sizeof(int); x++) {
cout << arr[x] << endl;
}
return 0;
}
|