这是自己自己总结的冒泡,快排,归并和堆排序的模板程序,自己如果记不清就可以来看看
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> paoOrder(vector<int>input) { //冒泡排序
vector<int>paoout;
int num = input.size();
for (int i = 0; i < num; i++) {
paoout.push_back(input[i]);
}
for (int i = 0; i < num-1; i++) {
for (int j = 1; j < num; j++) {
if (paoout[j] < paoout[j - 1]) {
int temp = paoout[j];
paoout[j] = paoout[j - 1];
paoout[j - 1] = temp;
}
}
}
return paoout;
}
void quickOrder(vector<int>&input,int low,int high) { //快排序
if (low >= input.size() || high >= input.size()) return;
if (low >= high)return;
int left = low;
int right = high;
int key = input[low];
while (left < right) {
while (input[right] >= key && left < right) {
right--;
}
while (input[left] <= key && left < right) {
left++;
}
if (left < right) {
int temp = input[left];
input[left] = input[right];
input[right] = temp;
}
}
input[low] = input[left];
input[left] = key;
quickOrder(input, low, left - 1);
quickOrder(input, left+1, high);
}
void merge(vector<int>&input, int left, int right, int mid) { //归并子部分
vector<int>temp;
for (int k = left; k <= right; k++) {
temp.push_back(input[k]);
}
int i = left;
int j = mid + 1;
for (int k = left; k <= right; k++) {
if (i > mid) {
input[k] = temp[j - left];
j++;
}
else if (j > right) {
input[k] = temp[i - left];
i++;
}
else if(temp[i-left]>temp[j-left]){
input[k] = temp[j - left];
j++;
}
else {
input[k] = temp[i - left];
i++;
}
}
}
void merge_sort(vector<int>&input, int left, int right) { //归并调用部分
if (left >= right) {
return;
}
int mid = (left + right) / 2;
merge_sort(input, left, mid);
merge_sort(input, mid + 1, right);
merge(input, left, right, mid);
}
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void MaxSort(vector<int>&input, int i, int n) { //堆排序
int j = 2 * i + 1;
int temp = input[i];
while (j < n) {
if (j + 1 < n && input[j] < input[j + 1]) {
j++;
}
if (temp > input[j]) {
break;
}
else {
input[i] = input[j];
i = j;
j = 2 * i + 1;
}
}
input[i] = temp;
}
void HeapSort(vector<int>&input, int n) { //堆循环
for (int i = n / 2 - 1; i >= 0; i--) {
MaxSort(input, i, n);
}
for (int i = n - 1; i >= 1; i--) {
swap(input[i], input[0]);
MaxSort(input, 0, i);
}
}
int main() {
vector<int>input = { 3,1,4,1,5,9,2,6,5,3,5,7 };
vector<int>paoout = paoOrder(input);
//quickOrder(input, 0, 11);
//merge_sort(input, 0, 11);
HeapSort(input, 12);
return 0;
}