0

I'm trying to build a max heap with a static method that's not object-oriented. This is what I have but when I call the method with the following array: {"C","D","A","B","E"}, it just returns the array as is, not in max heap order. I believe the output should be {"E","D","A","B","C"}. Any help would be awesome. Thank you in advance!

public static void buildMaxHeap(String[] x, int n) {
    int left = 2*n;
    int right = 2*n + 1;
    int max = n;
    for(int i = x.length/2; i >= 0; i--) {
    if(left <= x.length && x[left].compareTo(x[max]) > 0) {
        max = left;
    }
    if(right <= x.length && x[right].compareTo(x[max]) > 0) {
        max = right;
    }
    if(max != n) {
        String temp = x[n];
        x[n] = x[max];
        x[max] = temp;
        buildMaxHeap(x,max);
    }
    }
}
  • Sorry, I started with n=0, but you obviously start with n = 5, right? Well, if you debug your algorithm, it never gets inside any if, because your values are always out of bounds of the array (left and right are greater than x.length). So, you never change the array. – Igor Deruga Feb 16 '17 at 02:30

1 Answers1

0

Remember that as well as in coding in C and C++ you may experience problem with the uncorrect output while using cell's length as an operator, because of different size of initial cell and its pointer. It overwrites the cell's initial length and shorten it to 8 bytes.

Try to retrieve ASCII value of these characters, than use divide&conquer sorting algorythm to order your array cells' characters basing on their numerical value.

Getting ASCII value of the character: Get ASCII value at input word

Better and wider explained problem with cell's and its pointer's length: Why does a C-Array have a wrong sizeof() value when it's passed to a function?

Community
  • 1
  • 1
TheInvisibleMan
  • 56
  • 1
  • 11