tips:模板没啥用,不过是为了实践下模板,也可以将数组作为成员变量,模板意义就有点了.
template <typename T>
class mergeSort
{
private:
/* data */
public:
mergeSort(/* args */);
~mergeSort();
void sort(std::vector<T> &ans);
void sort(std::vector<T> &ans, std::vector<T> &temp, int left, int right);
void show(std::vector<T> &ans);
void merge(std::vector<T> &ans, std::vector<T> &temp, int left, int mid, int right);
};
template <typename T>
mergeSort<T>::mergeSort(/* args */)
{
std::cout << "无参构造函数" << std::endl;
}
template <typename T>
mergeSort<T>::~mergeSort()
{
std::cout << "析构函数" << std::endl;
}
template <typename T>
void mergeSort<T>::show(std::vector<T> &ans)
{
for (auto &x : ans)
std::cout << x << " ";
return;
}
template <typename T>
void mergeSort<T>::sort(std::vector<T> &ans)
{
std::vector<T> temp(ans.size(), 0);
sort(ans, temp, 0, ans.size()-1);
show(ans);
}
template <typename T>
void mergeSort<T>::sort(std::vector<T> &ans, std::vector<T> &temp, int left, int right)
{
if (left < right)
{
int mid = left+(right -left) / 2; //tips:与(left+right)/2一样,但是当数据量过于庞大时,left+right会溢出
sort(ans, temp, left, mid);
sort(ans, temp, mid + 1, right);
merge(ans, temp, left, mid, right);
}
//return ;
}
template <typename T>
void mergeSort<T>::merge(std::vector<T> &ans, std::vector<T> &temp, int left, int mid, int right)
{
int i = left, j = mid + 1, t = 0;
while (i <= mid && j <= right)
{
if (ans[i] <= ans[j])
temp[t++] = ans[i++];
else
temp[t++] = ans[j++];
}
while (i <= mid)
temp[t++] = ans[i++];
while (j <= right)
temp[t++] = ans[j++];
t = 0;
while (left <= right)
ans[left++] = temp[t++];
}
//template<typename T>