Sunday, April 24, 2016

merge sort C++

//ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

#define N 8

void Merge(int a[], int low, int m, int high)
{
static int b[N];
int i, j, k;
i = low;
j = m + 1;
k = i;
while (i <= m && j <= high)
{
if (a[i] < a[j]){
b[k] = a[i];
i++;
}
else
{
b[k] = a[j];
j++;
}                                                                                                                                       

k++;
}
while (i <= m)
{
b[k] = a[i];
i++;
k++;

}
while (j <= high)
{
b[k] = a[j];
j++;
k++;

}

for (k = low; k = high; k++)
{

a[k] = b[k];
}
}
void MySort(int a[], int low, int high)
{
if (low < high)
{
int m = (low + high) / 2;


MySort(a, low, m);
MySort(a, m + 1, high);


Merge(a, low, m, high);

}
}


int _tmain()
{
int a[N] = { 3, 8, 9, 7, 5, 2, 4, 1 };
MySort(a, 0, N - 1);
for (int k = 0; k < N; k++)
cout << a[k]<<endl;
system("pause");
return 0;
}



No comments:

Post a Comment