Sid*_*rth 2 c++ sorting data-structures
好吧,所以在努力调试之后,我终于放弃了.我是C++和数据结构的初学者,我正在尝试用C++实现Heap Sort.下面的代码给出了正整数的正确输出,但是当我尝试输入一些负整数时似乎失败了.
请在以下代码中指出任何错误/差异.此外,我们将很高兴收到有关该主题的任何其他建议/批评.
//Heap Sort
#include <iostream.h>
#include <conio.h>
int a[50],n,hs;
void swap(int &x,int &y)
{
int temp=x;
x=y;
y=temp;
}
void heapify(int x)
{
int left=(2*x);
int right=(2*x)+1;
int large;
if((left<=hs)&&(a[left]>a[x]))
{
large=left;
}
else
{
large=x;
}
if((right<=hs)&&(a[right]>a[large]))
{
large=right;
}
if(x!=large)
{
swap(a[x],a[large]);
heapify(large);
}
}
void BuildMaxHeap()
{
for(int i=n/2;i>0;i--)
{
heapify(i);
}
}
void HeapSort()
{
BuildMaxHeap();
hs=n;
for(int i=hs;i>1;i--)
{
swap(a[1],a[i]);
hs--;
heapify(1);
}
}
void main()
{
int i;
clrscr();
cout<<"Enter length:\t";
cin>>n;
cout<<endl<<"Enter elements:\n";
for(i=1;i<=n;i++) //Read Array
{
cin>>a[i];
}
HeapSort();
cout<<endl<<"Sorted elements:\n";
for(i=1;i<=n;i++) //Print Sorted Array
{
cout<<a[i];
if(i!=n)
{
cout<<"\t";
}
}
getch();
}
Run Code Online (Sandbox Code Playgroud)
我一直在阅读堆排序,但我无法掌握大部分概念,如果没有这个,我就无法解决上面的逻辑错误.