实现一些排序的算法当做模板吧!
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;
const int maxn = 105;
class Sort {
public:
vector<int>v;
Sort(vector<int>v2) {
v = v2;
}
~Sort() {
}
public:
void Merge(int left,int mid,int right);
void MergeSort(int left,int right);
void QuickSort(int left,int right);
void HeapSort(int left,int right);
void HeapDown(int fa,int right);
};
/*归并排序*/
void Sort::Merge(int left,int mid,int right) {
vector<int>v2;
int i = left,j = mid+1;
while(i <= mid && j <= right) {
if(v[i] > v[j]) {
v2.push_back(v[j++]);
} else {
v2.push_back(v[i++]);
}
}
while(i <= mid) {
v2.push_back(v[i++]);
}
while(j < right) {
v2.push_back(v[j++]);
}
j = left;
for(i = 0; i < v2.size(); i++) {
v[j++] = v2[i];
}
}
void Sort::MergeSort(int left,int right) {
if(left >= right) {
return;
}
int mid = (left+right)/2;
MergeSort(left,mid);
MergeSort(mid+1,right);
Merge(left,mid,right);
}
/*快速排序*/
void Sort::QuickSort(int left,int right) {
if(left >= right) {
return;
}
int low = left;
int high = right;
int val = v[left];
while(low < high) {
while(low < high && v[high] >= val) {
high--;
}
v[low] = v[high];
while(high > low && v[low] <= val) {
low++;
}
v[high] = v[low];
}
v[low] = val;
QuickSort(left,low-1);
QuickSort(low+1,right);
}
/*堆排序*/
void Sort::HeapDown(int k,int right) {
int val = v[k];
for(int i=2*k;i <= right;i*=2){
if(i<right&&v[i]>v[i+1]){
i++;
}
if(val < v[i])break;
else{
v[k] = v[i];
k = i;
}
}
v[k] = val;
}
void Sort::HeapSort(int left,int right) {
for(int i = right/2;i> 0;i--){
HeapDown(i,right);
}
int n = right;
for(int i = 1; i <= n; i++) {
printf("%d ",v[1]);
swap(v[1],v[right]);
HeapDown(1,--right);
}
}
int main() {
vector<int>v;
v.push_back(0);
for(int i = 10; i > 0; i--) {
v.push_back(i);
}
Sort A = Sort(v);
Sort B = Sort(v);
Sort C = Sort(v);
printf("原始序列:");
for(int i = 1; i <= 10; i++) {
printf("%d ",A.v[i]);
}
printf("\n");
A.MergeSort(1,10);
printf("归并排序后:");
for(int i = 1; i <= 10; i++) {
printf("%d ",A.v[i]);
}
printf("\n");
printf("快速排序后:");
B.QuickSort(1,10);
for(int i = 1; i <= 10; i++) {
printf("%d ",B.v[i]);
}
printf("\n堆排序后:");
C.HeapSort(1,10);
return 0;
}