0

I am trying to write a Heapsort method that only performs the sort within a given range passed into the method. The ranges low and high are passed in and these values correspond to values inside the heap, not indices of the heap. For example, the input array might be: 28 10 49 20 59 61 17 and if low = 49 and high = 61, the resulting array after the Heapsort would look like this: 28 10 20 49 59 61 17. The values outside of the range remain unchanged. I already have a working Heapsort method but my question is how can modify this method to sort within a passed range?

public static void heapSort(int[] array, int low, int high)
    {        
        // Build a maxHeap
        for(int i = array.length / 2; i >= 0; i--)
        {
            percolateDown(array, i, array.length);
        }

        // Heap sort
        for(int i = array.length - 1; i > 0; i--)
        {
            swap(array, 0, i);
            percolateDown(array, 0, i);
        }
    }

As you can see, my method accepts low and high but does not currently do anything with those values. I have tried keep a boolean flag to determine when the algorithm is in range and to only sort when that boolean is true. But this did not work. If somebody could help me that would be greatly appreciated.

Thanks!

  • What you want is not sorting. The values 41, 59 and 61 are already sorted in the original array. What you want is to rearrange the array so that all values between 49 and 61 are together. It is not clear what the position of the group should be. – M Oehm Apr 17 '16 at 05:30
  • No. Your question doesn't make sense. For example, you say that all values outside the range 49 to 61 remain unchanged, yet the 20 changes its position. And the subsequence of 49, 59 and 61, if it is isolated from the values outside the range, is already sorted. My comment wasn't dumb. Your reply, on the other hand ... – M Oehm Apr 18 '16 at 18:36

2 Answers2

0

You could create new array with values in the given range only, then heapsort new array only. Then replace the elements of the original array.

viviboox3
  • 309
  • 1
  • 6
  • 20
0
public static void main( String [ ] args ) {
        Integer[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1};
        heapsort(arr, 0, 4);
}

/**
 * Standard heapsort.
 * @param a an array of Comparable items.
 */
public static <AnyType extends Comparable<? super AnyType>> void heapsort(AnyType [ ] a, int low, int high) {
    for (int i = high / 2; i >= low; i--)  /* buildHeap */
        percDown( a, i, high);
    for (int i = high; i > low; i--) {
        swapReferences(a, low, i);         /* deleteMax */
        percDown(a, low, i);
    }
    System.out.println(Arrays.toString(a));
}