堆排序
作者: 冯向阳
时间限制: 1s
章节: 课程设计
问题描述
对于顺序存储的线性表,使用vector或数组,实现堆排序算法,并输出每趟的排序结果。
参考函数原型:(vector版本)
(1)//建堆
template<class ElemType>
void HeapSort( vector<ElemType> &A, int flag ); //flag:堆类型标记
(2)//堆调整(最大堆)
template<class ElemType>
void HeapASCAdjust( vector<ElemType> &A, int hole, int size );
(2)//堆调整(最小堆)
template<class ElemType>
void HeapDASCAdjust( vector<ElemType> &A, int hole, int size );
输入说明
第一行:顺序表A的数据元素的数据类型标记(0:int,1:double,2:char,3:string)
第二行:堆类型标记(1:大根堆,2:小根堆)
第三行:待排序顺序表A的数据元素(数据元素之间以空格分隔)
输出说明
如第一行输入值为0、1、2、3之外的值,直接输出“err”
否则:
第一行:第一趟的排序结果(数据元素之间以","分隔)
第三行:第二趟的排序结果(数据元素之间以","分隔)
...
第n行:最终的排序结果(数据元素之间以","分隔)
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
template<class ElemType>
void HeapASCAdjust(vector<ElemType>& A, int hole, int size) {
ElemType temp = A[hole];
int child;
for (; 2 * hole + 1 < size; hole = child) {
child = 2 * hole + 1;
if (child + 1 < size && A[child] < A[child + 1]) {
child++;
}
if (temp < A[child]) {
A[hole] = A[child];
}
else {
break;
}
}
A[hole] = temp;
}
template<class ElemType>
void HeapDASCAdjust(vector<ElemType>& A, int hole, int size) {
ElemType temp = A[hole];
int child;
for (; 2 * hole + 1 < size; hole = child) {
child = 2 * hole + 1;
if (child + 1 < size && A[child] > A[child + 1]) {
child++;
}
if (temp > A[child]) {
A[hole] = A[child];
}
else {
break;
}
}
A[hole] = temp;
}
template<class ElemType>
void HeapSort(vector<ElemType>& A, int flag) {
int size = A.size();
if (flag == 1) { // 大根堆
for (int i = size / 2 - 1; i >= 0; --i) {
HeapASCAdjust(A, i, size);
}
}
else if (flag == 2) { // 小根堆
for (int i = size / 2 - 1; i >= 0; --i) {
HeapDASCAdjust(A, i, size);
}
}
// 输出建立堆后的数组
for (int j = 0; j < size; ++j) {
if (j > 0) cout << ",";
cout << A[j];
}
cout << endl;
for (int i = size - 1; i > 0; --i) {
swap(A[0], A[i]);
if (flag == 1) {
HeapASCAdjust(A, 0, i);
}
else if (flag == 2) {
HeapDASCAdjust(A, 0, i);
}
for (int j = 0; j < size; ++j) {
if (j > 0) cout << ",";
cout << A[j];
}
cout << endl;
}
}
template<class ElemType>
void readInput(vector<ElemType>& A) {
string line;
getline(cin, line);
istringstream iss(line);
ElemType value;
while (iss >> value) {
A.push_back(value);
}
}
int main() {
string type;
getline(cin, type);
if (type != "0" && type != "1" && type != "2" && type != "3") {
cout << "err" << endl;
return 0;
}
int flag;
cin >> flag;
cin.ignore();
if (flag != 1 && flag != 2) {
cout << "err" << endl;
return 0;
}
if (type == "0") {
vector<int> A;
readInput(A);
HeapSort(A, flag);
}
else if (type == "1") {
vector<double> A;
readInput(A);
HeapSort(A, flag);
}
else if (type == "2") {
vector<char> A;
readInput(A);
HeapSort(A, flag);
}
else if (type == "3") {
vector<string> A;
readInput(A);
HeapSort(A, flag);
}
return 0;
}