Plus One - Leet Code Solution
Problem Statement Given a non-empty array of digits representing a non-negative…
July 03, 2019
This is another very useful sorting algorithm based on Heap data structure. Read more about Heap Data Structure
In this algorithn, we first prepare heap which satisfies max-heap property. Once we get out max heap ready. We get maximum element at the top. We swap this element with the last index element. And, reduce heapsize by one. Now, since we have put a newer element on top. We will just run max_heapify() algorithm on this array with new heapsize.
Finally we get the sorted array.
In a loop starting from last index
See the code here:
public class HeapSort {
private int[] arr;
private int heapsize;
public HeapSort(int[] arr) {
this.arr = arr;
this.heapsize = this.arr.length;
}
private int getLeftChild(int index) {
return (index * 2) + 1;
}
private int getRightChild(int index) {
return (index * 2) + 2;
}
private void max_heapify(int index) {
int l = this.getLeftChild(index);
int r = this.getRightChild(index);
int indexOfLargest = index;
if (l < this.heapsize && this.arr[l] > this.arr[index]) {
indexOfLargest = l;
}
if (r < this.heapsize && this.arr[r] > this.arr[indexOfLargest]) {
indexOfLargest = r;
}
if (indexOfLargest != index) {
ArrayUtils.swap(this.arr, index, indexOfLargest);
this.max_heapify(indexOfLargest);
}
}
private void buildMaxHeap() {
for (int i=this.heapsize/2; i>=0; i--) {
this.max_heapify(i);
}
}
public void doHeapSort() {
this.buildMaxHeap();
int l = this.arr.length;
for (int i=l-1; i>0; i--){
ArrayUtils.swap(this.arr, 0, i);
this.heapsize--;
this.max_heapify(0);
}
}
}
The algorithm runs on O(n log n) in worst/average case.
Problem Statement Given a non-empty array of digits representing a non-negative…
Problem Statement Determine if a 9x9 Sudoku board is valid. Only the filled…
This algorithm is very efficient one, and is classic example of Divide and…
A Binary tree is a data structure which has two children nodes attached to it…
Min Priority Queue is a data structure which manage a list of keys(values). And…
Problem Statement You are given an n x n 2D matrix representing an image, rotate…
Introduction Strapi is a backend system provides basic crud operations with…
Introduction I had to create many repositories in an Github organization. I…
Introduction I was trying to download some youtube videos for my kids. As I have…
Introduction In this post, we will explore some useful command line options for…
Introduction In this post, we will see how we can apply a patch to Python and…
Introduction We will introduce a Package Manager for Windows: . In automations…