Skip to content

Instantly share code, notes, and snippets.

@JankDev
Created March 23, 2019 18:50
Show Gist options
  • Save JankDev/7ac0171944c6c7d71e4f14dab3160c79 to your computer and use it in GitHub Desktop.
Save JankDev/7ac0171944c6c7d71e4f14dab3160c79 to your computer and use it in GitHub Desktop.
HeapSort implementation java
package nauka;
import java.util.Random;
public class HeapSort {
private static int heapSize;
private static int right(int index) {
return (index << 1) + 2;
}
private static int left(int index) {
return (index << 1) + 1;
}
private static final void swap(int index1, int index2, int[] arr) {
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
private static void heapify(int[] arr, int index) {
int left = left(index);
int right = right(index);
int largest;
if (left < heapSize && arr[left] > arr[index])
largest = left;
else
largest = index;
if (right < heapSize && arr[right] > arr[largest])
largest = right;
if (largest != index) {
swap(largest,index,arr);
heapify(arr,largest);
}
}
private static void buildMaxHeap(int[] arr) {
heapSize = arr.length;
for(int i=(arr.length-1)/2;i>=0;i--) heapify(arr, i);
}
static void heapSort(int[] arr) {
buildMaxHeap(arr);
for(int i=arr.length-1;i>0;i--) {
swap(i,0,arr);
heapSize--;
heapify(arr,0);
}
}
public static void main(String[] args) {
Random r = new Random();
int[] arr = r.ints(0,50).limit(20).toArray();
for(int n:arr) System.out.printf("%d ",n);
System.out.println();
heapSort(arr);
for(int n:arr) System.out.printf("%d ",n);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment