Function rgsl::sort::objects::heapsort

source ·
pub fn heapsort<T>(array: &mut [T], compare: comparison_fn<T>)
Expand description

This function sorts the count elements of the array array, each of size size, into ascending order using the comparison function compare. The type of the comparison function is defined by,

i32 (*comparison_fn<T>) (a: &[T], b: &[T])

A comparison function should return a negative integer if the first argument is less than the second argument, 0 if the two arguments are equal and a positive integer if the first argumentis greater than the second argument.

For example, the following function can be used to sort doubles into ascending numerical order.

fn compare_doubles(a: &[f64], b: &[f64]) -> i32 {
   if (a[0] > b[0])
      return 1;
   else if (a[0] < b[0])
      return -1;
   else
      return 0;
}

The appropriate function call to perform the sort is,

heapsort(array, compare_doubles);

Note that unlike qsort the heapsort algorithm cannot be made into a stable sort by pointer arithmetic. The trick of comparing pointers for equal elements in the comparison function does not work for the heapsort algorithm. The heapsort algorithm performs an internal rearrangement of the data which destroys its initial ordering.