堆排序

#include<iostream>
#include<regex>
#include<string.h>
#include<string>
#include<algorithm>
#include<vector>
#include<stdlib.h>
using namespace std;
bool regexMatch(string str) {//正则表达式
 string pattern = { "[0-9]{1,}" };
 regex Regex(pattern);
 bool matched = regex_match(str,Regex);
 return matched;
}
int digitalConversion(string str) {//数字转换
 return stoi(string(str));
}
void inIt(vector<string> &str, vector<int> &integer) {//传引用
 string a;
 cout << "请输入一个正整数:\n";
 cin >> a;
 while (!regexMatch(a)) {
  cout << "输入有误,请重新输入n:\n";
  cin >> a;
 }
 cout << "请输入"<< digitalConversion(a)<<"个正整数:\n";
 string b;
 for (int i = 0; i <digitalConversion(a) ; i++) {
  cin >> b;
  if (!regexMatch(b)) {
   cout << "输入错误,请重新输入:\n";
   i--;
   continue;
  }
  integer.push_back(digitalConversion(b));
 }
}
void heapAdjust(vector<int> &integer,int i,int len) {
 int left, right, j;
 while ((left = 2 * i + 1) <= len) {
  right = left + 1;
  j = left;
  if (j < len&&integer[left] < integer[right]) {
   j++;
  }
  if (integer[i] < integer[j]) {
   swap(integer[i], integer[j]);
  }
  else break;
  i = j;
 }
}
void  heapSort(vector<int> &integer) {
 int len = integer.size() - 1;
 for (int i = len / 2 - 1; i >= 0; i--) {//堆构造
  heapAdjust(integer, i, len);
 }
 while (len >= 0) {
  swap(integer[0], integer[len--]);//将堆顶元素与尾节点交换后,长度减1,尾元素最大
  heapAdjust(integer, 0, len); //对堆进行调整
 }
}

int main() {
 vector<string>str;
 vector<int>integer;
 inIt(str, integer);
 heapSort(integer);
 for (int i = 0; i < integer.size(); i++) {
  cout << integer[i] << " ";
 }
 cout << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值