Skip to content

Instantly share code, notes, and snippets.

@emsesc
Created March 26, 2023 00:08
Show Gist options
  • Save emsesc/53052a8f34c29089fd53ee705f965147 to your computer and use it in GitHub Desktop.
Save emsesc/53052a8f34c29089fd53ee705f965147 to your computer and use it in GitHub Desktop.
public void insert(int p){
//Hint: remember to update size. Also, remember that we skip index 0 in the array.
/*Your code here */
if (this.size == 0) {
// if array is empty
elts[1] = p;
} else if (this.size != max) {
// if the size isn't already at max
// set spot at the end of heap to new value
elts[size + 1] = p;
// recursively bubble up the last value to the right place
bubbleUp(size + 1);
}
this.size ++;
}
private void bubbleUp(int child) {
int parent = child/2;
// calculate parent of child element
if (parent > 0 && elts[parent] > elts[child]) {
// if parent is still in range and is GREATER than the child
int temp = elts[child];
elts[child] = elts[parent];
elts[parent] = temp;
// swap element and continue to bubble up
bubbleUp(parent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment