> For the complete documentation index, see [llms.txt](https://nitinranganath.gitbook.io/data-structures/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nitinranganath.gitbook.io/data-structures/heap/deleting-in-a-heap.md).

# Deleting in a Heap

### Procedure :

* Copy the last element to root i.e index 1.
* Shift the root element to last element of heap.
* Set i as 1 (root) and j as 2\*i (left child of root).
* Perform the following until j < size - 1.
* Find which of the child is greater.
* Set j to point on that child.
* If the child element (j) is greater than parent element (i), swap them.
* Set i as j and j as 2\*j after each iteration.&#x20;

```c
int deleteFromHeap(int h[], int size) {

	// Copy last element to root and first element to last place
	int lastElement = h[size];
	int firstElement = h[1];
	h[1] = lastElement;
	h[size] = firstElement;

	// Keep i at root and j at left child of root initially
	int i = 1, j = 2*i;

	while(j < size-1) {

		// Find out if left child is greater or right child
		if (h[j+1] > h[j]) 
			j = j + 1;
	
		// If child is greater than parent, interchange
		if (h[j] > h[i]) {
			int temp = h[i];
			h[i] = h[j];
			h[j] = temp;
			// Set i to j and j to left child of j
			i = j;
			j = 2*j;
		} else {
			break;
		}
	}
	return firstElement;

}
```

**By calling the same function n times, heap sort can be implemented.**


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://nitinranganath.gitbook.io/data-structures/heap/deleting-in-a-heap.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
