Skip to content

Add heapsort algoritham. #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions Sorting algorithms/Heapsort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import java.util.*;

public class Heapsort {

public static void buildheap(int []arr) {

for(int i=(arr.length-1)/2; i>=0; i--){
heapify(arr,i,arr.length-1);
}
}

public static void heapify(int[] arr, int i,int size) {
int left = 2*i+1;
int right = 2*i+2;
int max;
if(left <= size && arr[left] > arr[i]){
max=left;
} else {
max=i;
}

if(right <= size && arr[right] > arr[max]) {
max=right;
}
// If max is not current node, exchange it with max of left and right child
if(max!=i) {
exchange(arr,i, max);
heapify(arr, max,size);
}
}

public static void exchange(int[] arr,int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}

public static int[] heapSort(int[] arr) {

buildheap(arr);
int sizeOfHeap=arr.length-1;
for(int i=sizeOfHeap; i>0; i--) {
exchange(arr,0, i);
sizeOfHeap=sizeOfHeap-1;
heapify(arr, 0,sizeOfHeap);
}
return arr;
}

public static void main(String[] args) {

Scanner s = new Scanner (System.in);
System.out.println("Enter number of elements");
int n = s.nextInt();
int a[] = new int[n];
for (int i=0;i<n;i++) {
a[i] = s.nextInt();
}
a=heapSort(a);
System.out.println("After Heap Sort : ");
System.out.println(Arrays.toString(a));
}
}