常用的排序算法二(归并排序)
程序员文章站
2022-03-02 08:14:11
...
归并排序
将数组分为左右两部分
将左右部分分别排好序(递归见代码sortProcess函数)
建立辅助数组,将左右两边排好序的子数组按照大小放入辅助数组里,然后将辅助数组拷贝到原数组中。见代码merge函数
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// 归并排序
/*
* 1. 将数组分为左右两部分,左右边分别排好序
* 2. 建立辅助数组,将左右两边排好序的子数组按照大小放入辅助数组里
* 3. 将辅助数组拷贝到原数组中
* */
void merge(vector<int>& example, int left, int mid, int right) {
vector<int> tmp;
int p1 = left, p2 = mid + 1;
while (p1 <= mid && p2 <= right) {
if (example[p1] < example[p2]) {
tmp.push_back(example[p1]);
p1++;
} else {
tmp.push_back(example[p2]);
p2++;
}
}
while (p1 <= mid) {
for (int i = p1; i <= mid; i++) {
tmp.push_back(example[i]);
p1++;
}
}
while (p2 <= right) {
for (int i = p2; i <= right; i++) {
tmp.push_back(example[i]);
p2++;
}
}
for (int i = 0; i < tmp.size(); i++) {
example[left+i] = tmp[i];
}
}
void sortProcess(vector<int>& example, int left, int right) {
if (left == right) {
return;
}
int mid = left + ((right - left) >> 1);
sortProcess(example, left, mid);
sortProcess(example, mid + 1, right);
merge(example, left, mid, right);
}
void mergeSort(vector<int>& example) {
if (example.empty() || example.size() == 1) {
return;
}
sortProcess(example, 0, example.size() - 1);
}
};
int main()
{
vector<int> example = {1, 12, 9, 3, 6};
cout << "排序前的数组为: ";
for (int i = 0; i < example.size() - 1; i++) {
cout << example[i] << ", ";
}
cout << example[example.size()-1] << endl;
cout << "----------------------------" << endl;
Solution su;
su.mergeSort(example);
cout << "排序后的数组为: ";
for (int i = 0; i < example.size() - 1; i++) {
cout << example[i] << ", ";
}
cout << example[example.size()-1] << endl;
return 0;
}
上一篇: 排序算法之快速排序(JAVA)
下一篇: 排序算法之基数排序(桶排序)JAVA