Problems implementing Heapsort algorithm in R


Hendra

I want to create my own Heapsort algorithm in R.
this is my code

heapify <- function(array, n, i)
{
  parent <- i
  leftChild <- 2 * i + 1
  rightChild <- 2 * i + 2

  if ((leftChild < n) & (array[parent] < array[leftChild]))
  {
    parent = leftChild
  }

  if ((rightChild < n) & (array[parent] < array[rightChild]))
  {
    parent = rightChild
  }

  if (parent != i)
  {
    array = replace(array, c(i, parent), c(array[parent], array[i]))
    heapify(array, n, parent)
  }
}

heapSort <- function(array)
{
  n <- length(array)

  for (i in (n+1):1)
  {
    heapify(array, n, i)
  }

  for (i in n:1)
  {
    array = replace(array, c(i, 0), c(array[0], array[i]))
    heapify(array, i, 1)
  }
  print(array)
}

However, the implementation seems to be incorrect. Here is an example of input and output.

array <- c(5, 14, 3, 70, 64)
heapSort(array)

Output: [1]  5 14  3 70 64

It took me a long time and I don't know what the problem is. I would appreciate any tips or tricks.

Joseph Wood

My guess is that you are trying to convert the algorithm posted on GeeksforGeeks where they implement it in many zero-based languages . This is one of the sources of the problem (R starts indexing at 1 instead of 0).

Basic zero index problem:

Example 1:

                         ## We also need to swap these indices
array = replace(array, c(i, 0), c(array[0], array[i]))
heapify(array, i, 1)

Should be:

array <- replace(array, c(i, 1), array[c(1, i)])
array <- heapify(array, i, 1)

Example 2:

leftChild <- 2 * i + 1
rightChild <- 2 * i + 2

Should be:

leftChild <- 2 * (i - 1) + 1
rightChild <- 2 * (i - 1) + 2

Assumptions by reference

In R, you cannot pass objects by reference (see this question and answer, Can you pass by reference in R ? ). This means, when we call a recursive function, it must be allocated, and the recursive function must return something.

Before heapifywe must return array. Likewise, every call to heapifyus must be assigned arrayto an output.

Here is the modified code:

heapify <- function(array, n, i)
{
    parent <- i
    leftChild <- 2 * (i - 1) + 1
    rightChild <- 2 * (i - 1) + 2

    if ((leftChild < n) & (array[parent] < array[leftChild]))
    {
        parent <- leftChild
    }

    if ((rightChild < n) & (array[parent] < array[rightChild]))
    {
        parent <- rightChild
    }

    if (parent != i) {
        array <- replace(array, c(i, parent), array[c(parent, i)])
        array <- heapify(array, n, parent)
    }

    array
}

heapSort <- function(array)
{
    n <- length(array)

    for (i in floor(n / 2):1) {
        array <- heapify(array, n, i)
    }

    for (i in n:1) {
        array <- replace(array, c(i, 1), array[c(1, i)])
        array <- heapify(array, i, 1)
    }

    array
}

Here are some tests (note that this algorithm is extremely inefficient in R. Don't try to use a much larger vector than below):

array <- c(5, 14, 3, 70, 64)
heapSort(array)
[1]  3  5 14 64 70

set.seed(11)
largerExample <- sample(1e3)

head(largerExample)
[1] 278   1 510  15  65 951

identical(heapSort(largerExample), 1:1e3)
[1] TRUE

Related


Problems implementing Heapsort algorithm in R

Hendra I want to create my own Heapsort algorithm in R. this is my code heapify <- function(array, n, i) { parent <- i leftChild <- 2 * i + 1 rightChild <- 2 * i + 2 if ((leftChild < n) & (array[parent] < array[leftChild])) { parent = leftChild

Problems with HeapSort

Air My task is to write code to heapsort based on pseudocode. It should heap sort the input array ( 4 3 2 5 6 7 8 9 12 1) and then print it using the printHeap method. I know that printHeap works because I've used it with a method called buildHeap (to build th

Problems with HeapSort

Air My task is to write code to heapsort based on pseudocode. It should heap sort the input array ( 4 3 2 5 6 7 8 9 12 1) and then print it using the printHeap method. I know that printHeap works because I've used it with a method called buildHeap (to build th

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Problems implementing Dijkstra's algorithm

Ude I am trying to solve a problem where I need to find the maximum distance between two points in a graph. I wrote this code to implement Dijkstra's algorithm (obviously by changing minimization to maximization), but it doesn't seem to work in some cases, and

Implementing Algorithm X in R

Erin McGee I'm looking to implement something like Knuth's Algorithm X in R. Problem: I have an axk matrix A, n >= k, whose real-valued entries represent costs. Typically, both n and k will be very small (n < 10, k < 5). I want to find a mapping of rows to col

Implementing Algorithm X in R

Erin McGee I'm looking to implement something like Knuth's Algorithm X in R. Problem: I have an axk matrix A, n >= k, whose real-valued entries represent costs. Typically, both n and k will be very small (n < 10, k < 5). I want to find a mapping of rows to col

Algorithm Description - Is it heapsort or quicksort?

post I'm having trouble telling whether this algorithm is heapsort or quicksort. Lets say I have an algorithm for which I don't have the source code - it's not stable, performs well on large datasets, and has similar runtimes on ordered and unordered sets. Wit

Problems implementing MLE estimation in the bbmle package (for R)

will I am trying to validate the MLEs for $\alpha$ , $\beta$ and $\lambda$ obtained for the Logistic-Lomax distribution by Zubair et al. in their paper titled A Study of Logistic-Lomax Distribution when using Dataset 1 . The paper uses the following code to do

R: Implementing my own gradient boosting algorithm

YQW : I am trying to write my own gradient boosting algorithm. I understand that there are similar existing packages , gbmbut xgboost,I would like to understand how the algorithm works by writing my own. I am working with a irisdataset and the results are Sepa

R: Implementing my own gradient boosting algorithm

YQW : I am trying to write my own gradient boosting algorithm. I understand that there are similar existing packages , gbmbut xgboost,I would like to understand how the algorithm works by writing my own. I am working with a irisdataset and the results are Sepa

Heapsort algorithm using min-heap

Mars When I heapsortuse a implementation, min-heapit sorts the array from largest to smallest. Is this a desired output heapsortto use min-heap? Sorting after sorting to output the smallest to largest value seems redundant, since it heapitself has a smallest t

Problems implementing recursive function in R-Fisher scoring

Pocketlemon5 I'm trying to implement Fisher scoring on simulated iid Poisson data, but I'm getting a stack overflow error. I did some simple prints from the function and found that the guess value didn't change after the first iteration. fs_pois <- function(da

Problems implementing recursive function in R-Fisher scoring

Pocketlemon5 I'm trying to implement Fisher scoring on simulated iid Poisson data, but I'm getting a stack overflow error. I did some simple prints from the function and found that the guess value didn't change after the first iteration. fs_pois <- function(da

Problems implementing recursive function in R-Fisher scoring

Pocketlemon5 I'm trying to implement Fisher scoring on simulated iid Poisson data, but I'm getting a stack overflow error. I did some simple prints from the function and found that the guess value didn't change after the first iteration. fs_pois <- function(da

Problems implementing recursive function in R-Fisher scoring

Pocketlemon5 I'm trying to implement Fisher scoring on simulated iid Poisson data, but I'm getting a stack overflow error. I did some simple prints from the function and found that the guess value didn't change after the first iteration. fs_pois <- function(da

Problems implementing recursive function in R-Fisher scoring

Pocketlemon5 I'm trying to implement Fisher scoring on simulated iid Poisson data, but I'm getting a stack overflow error. I did some simple prints from the function and found that the guess value didn't change after the first iteration. fs_pois <- function(da

Problems implementing recursive function in R-Fisher scoring

Pocketlemon5 I'm trying to implement Fisher scoring on simulated iid Poisson data, but I'm getting a stack overflow error. I did some simple prints from the function and found that the guess value didn't change after the first iteration. fs_pois <- function(da

Error implementing Faster R-CNN object detection algorithm

mark I am trying to implement Faster R-CNN object detection algorithm and I am getting an unusual error. When trying to call the function in train_one_epochthis colab tutorial , I got the error mentioned here . The exact error I'm getting is:loss_dict = model(