// ConsoleApplication55.cpp : 定义控制台应用程序的入口点。
//原地归并排序
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
//将长度为n的数组逆转
void reverse(int *arr, int n){
for (int i = 0; i < (n / 2); i++){
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
}
//将含有n个元素的数组循环左移i位
void exchange(int *arr, int n, int i){
reverse(arr,i);
reverse(arr + i, n - i);
reverse(arr, n);
}
void merge(int *arr, int begin, int mid, int end){
int i = begin, j = mid, k = end;
while (i < j && j <= k){
while (i < j && arr[i] <= arr[j])
{
i++;
}
int step = 0;
while (j <= k && arr[j] <= arr[i])
{
j++;
step++;
}
exchange(arr + i, j - i, j - i - step);
i += step;
}
}
void MergeSort(int *arr, int l, int r){
if (l < r){
int mid = (l + r) / 2;
MergeSort(arr, l, mid);
MergeSort(arr, mid+1, r);
merge(arr, l, mid+1, r);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[7] = { 4, 6, 3, 36, 24, 2, 45 };
MergeSort(a, 0, 6);
//exchange(a, 7,3);
for (int i = 0; i < 7; i++)
cout << a[i] << " ";
system("pause");
return 0;
}
<img src="https://img-blog.csdn.net/20160821200138296?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />