C++实现——归并排序
代码中展示了归并排序的C++版本的实现,并在其中使用了智能指针unique_ptr的数组形式。
#include<iostream>
#include<climits>
#include<memory>
using namespace std;
void merge(int arr[], int start, int mid, int end);
void merge_sort(int arr[], int start, int end);
int main()
{
int arr[] = {3,2,5,1,6};
int length = sizeof(arr) / sizeof(arr[0]);
merge_sort(arr,0,length);
for (int x : arr) cout << x << ' ';
return 0;
}
void merge_sort(int arr[], int start, int end)
{
if (end-start>1)
{
int mid = (start + end) / 2;
merge_sort(arr, start, mid);
merge_sort(arr, mid, end);
merge(arr, start, mid, end);
}
}
void merge(int arr[], int start, int mid, int end)
{
int len1 = mid - start + 1;
int len2 = end - mid + 1;
unique_ptr<int[]> arr1(new int[len1]);
unique_ptr<int[]> arr2(new int[len2]);
for (int i = start; i < mid; i++) arr1[i-start] = arr[i];
arr1[len1 - 1] = INT_MAX;
for (int i = mid; i < end; i++) arr2[i-mid] = arr[i];
arr2[len2 - 1] = INT_MAX;
int j = 0, k = 0;
for (int i = start; i < end; i++)
{
if (arr1[j] < arr2[k])
{
arr[i] = arr1[j];
j++;
}
else
{
arr[i] = arr2[k];
k++;
}
}
}