排序算法06-归并排序
目录
归并排序
void mergeSort(vector<int>&arr, int start, int end)
{
if (arr.empty()||start >= end)
return;
int mid = (end + start) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid+1, end);
merge(arr, start, mid, end);
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i]<<" ";
}
cout << endl;
}
///对两个数组进行合并 并排序
void merge(vector<int>&arr, int start, int mid, int end)
{
vector<int> tmp;
int i = start;
int j = mid+1;
while (i <= mid&&j <= end)
{
if (arr[i] <= arr[j])
tmp.push_back(arr[i++]);
else
tmp.push_back(arr[j++]);
}
while(i <= mid)
tmp.push_back(arr[i++]);
while (j <= end)
tmp.push_back(arr[j++]);
for (int i = 0; i < tmp.size(); i++)
arr[start + i] = tmp[i];
}