c++实现归并排序
#include <iostream>
using namespace std;
void merge(int start, int end, int* data)
{
int result[100];
int leftlength = (end-start)/2+1;
int leftindex = start;
int rightindex = leftlength + start;
int resultindex = start;
while (leftindex < leftlength + start && rightindex < end+1 )
{
if (data[leftindex] > data[rightindex])
{
result[resultindex++] = data[rightindex++];
}
else
{
result[resultindex++] = data[leftindex++];
}
}
while (leftindex < leftlength + start)
{
result[resultindex++] = data[leftindex++];
}
while (rightindex < end + 1)
{
result[resultindex++] = data[rightindex++];
}
for (int i = start; i <= end; i++)
{
data[i] = result[i];
}
}
void merge_sort(int start, int end, int*data)
{
if (end - start == 0)
{
}
else if(end-start==1)
{
if (data[start] > data[end])
{
int temp = data[start];
data[start] = data[end];
data[end] = temp;
}
}
else
{
merge_sort(start, (end - start) / 2+start, data);
merge_sort((end - start) / 2 + 1+start, end, data);
merge(start, end, data);
}
}
int main()
{
int data[] = { 1,3,2,5,9,4,8,6,7,11,68,59,12,6};
merge_sort(0, 13, data);
for (int i = 0; i < 14; i++)
{
cout << data[i] << " ";
}
}