归并排序
归并排序代码
MergeSort.hpp
//
// Created by Administrator on 2021/7/28.
//
#ifndef C__TEST01_MERGESORT_HPP
#define C__TEST01_MERGESORT_HPP
#include <vector>
#include <iostream>
using namespace std;
class MergeSort {
public:
MergeSort(vector<int> An);
void process(vector<int> &A, int L, int R);
void merge(vector<int> &A, int L, int mid, int R);
private:
vector<int> A;
};
MergeSort::MergeSort(vector<int> An) :
A(An){
A.resize(An.size());
}
void MergeSort::process(vector<int> &A, int L, int R) {
if(L == R){
return;
}
int mid = L + ((R-L) >> 1);
process(A, L, mid);
process(A, mid+1, R);
merge(A, L, mid, R);
}
void MergeSort::merge(vector<int> &A, int L, int mid, int R) {
vector<int> arr(R-L+1);
int i = 0;
int p1 = L;
int p2 = mid+1;
while(p1 <= mid && p2 <= R){
arr[i++] = A[p1] <= A[p2]?A[p1++]:A[p2++];
}
while(p1 <= mid){
arr[i++] = A[p1++];
}
while(p2 <= R){
arr[i++] = A[p2++];
}
for(i = 0; i<arr.size(); ++i){
A[L+i] = arr[i];
}
}
#endif //C__TEST01_MERGESORT_HPP
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈