为什么这个堆排序没有给出正确的输出。输出应该是一个排序的数组,但一些随机输出即将到来。这里是链接https://ideone.com/4eD289。也可以任何人查看此代码,以便它使用现代c ++功能。你有什么建议
#include<iostream>
#include<algorithm>
#include<vector>
int max_heapify(std::vector<int>& v, int i){
int l = 2*i;
int r = 2*i + 1;
int largest = 0;
if( (l < v.size()) && (v[l] > v[i]) ){
largest = l;
}
else{
largest = i;
}
if ( (r<v.size()) && (v[r] > v[largest]) ){
largest = r;
}
if ( largest != i){
std::swap(v[i], v[largest]);
max_heapify(v, largest);
}
return 0;
}
int build_max_heap(std::vector<int> &v){
for( int i = v.size()/2; i >= 0; i--){
max_heapify(v, i);
}
return 0;
}
int heap_sort(std::vector<int>& v){
build_max_heap(v);
int length = v.size();
for( int i = length-1 ; i>=1; i--)
std::swap(v[0], v[i]);
length--;
max_heapify(v, v[length]);
}
int main(){
std::vector<int> v = { 1, 2, 9, 8, 3, 4, 7, 6, 5};
heap_sort(v);
for(auto& e : v) std::cout<<e<<" ";
return 0;
}
答案 0 :(得分:0)
更正:
更正了您可能正在查找的所需堆排序的代码。
#include<iostream>
#include<algorithm>
#include<vector>
int max_heapify(std::vector<int>& v, int i,int len){
int l = 2*i;
int r = 2*i + 1;
int largest = 0;
if( (l < len) && (v[l] > v[i]) ){
largest = l;
}
else{
largest = i;
}
if ( (r<len) && (v[r] > v[largest]) ){
largest = r;
}
if ( largest != i){
std::swap(v[i], v[largest]);
max_heapify(v, largest,len);
}
return 0;
}
int build_max_heap(std::vector<int> &v){
for( int i = v.size()/2; i > 0; i--){
max_heapify(v, i,v.size());
}
return 0;
}
int heap_sort(std::vector<int>& v){
build_max_heap(v);
int length = v.size();
for( int i = length-1 ; i>=1; i--){
std::swap(v[1], v[i]);
length--;
max_heapify(v, 1,i);
}
}
int main(){
std::vector<int> v = { 0 \* NULL entry *\ , 1, 2, 9, 8, 3, 4, 7, 6, 5};
heap_sort(v);
for(auto& e : v) std::cout<<e<<" ";
return 0;
}