开发者

heapsort implementation in c++

开发者 https://www.devze.com 2023-04-10 05:53 出处:网络
i have following code for heapsort #include <iostream> using namespace std; void exch(int a[],int i,int j){

i have following code for heapsort

#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
      int s=a[i];
      a[i]=a[j];
      a[j]=s;
        }
void sink(int a[],int k,int n){
 //int n=sizeof(a)/sizeof(int);
 while(2*k<=n){
  int j=2*k;
  if (j<n && (a[j]<a[j+1])) j++;
  if (a[k]>=a[j]) break;
  exch(a,k,j);
  k=j;


 }
   }


  void heapsort(int a[]){
   int n=sizeof(a)/sizeof(int);
    for (int k=n/2;k>=1;k--)
             sink(a,k,n);
    while(n>1){
     exch(a,1,n--);
                sink(a,开发者_JS百科1,n);


    }

        }
int main(){

    int  a[]={12,3,5,1,67,10,9.20};
    int n=sizeof(a)/sizeof(int);
    heapsort(a);

           for (int i=0;i<n;i++){
            cout<<a[i]<<"  ";


           }
              return 0;


}

but result it shows me looks like this

12  3  5  1  67  10  9  Press any key to continue . . .

also look that in my array total number is 8 and here it shows me 7 as output, i think core of this problem should be this

1>c:\users\datuashvili\documents\visual studio 2010\projects\heap\heap\heap.cpp(36): warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data

it seams that possible loss of data while converting from double to int force code works incorrectly,am i correct or wrong?please help me


You wrote a . instead of a , between the 9 and 20:

int  a[]={12,3,5,1,67,10,9.20};

This results in 7 numbers, the last of which is the double 9.20 which gets converted to an int.

Additionally, this code is wrong:

void heapsort(int a[]){
    int n=sizeof(a)/sizeof(int);

Array arguments are actually passed as pointers, so sizeof(a) won't give you the correct result. You should pass in the array size as an additional parameter instead.


One problem I can see immediately is here:

void heapsort(int a[]){
   int n=sizeof(a)/sizeof(int);

You cannot pass an entire array as a parameter to a function in C/C++. The parameter syntax int a[] is, of course, confusing, but in fact it's equivalent to int* a. heapsort() can't know the size of the array to which a points. You have to pass the size in as a separate parameter.


In addition to all the other comments (sizeof(a), passing [] as arguments, having a . in the init-list), you want to write C++-code, right? But it looks quite C'ish, except for the iostream. Thereore:

  • use std::vector<int> from #include <vector> (add elements with push_back for example)
  • pass it as as a reference, i.e. void heapsort(std::vector<int> &a)
  • consider using std::swap( a[i], a[j] ); instead of exch
0

精彩评论

暂无评论...
验证码 换一张
取 消