Skip to content

Commit

Permalink
heapSort
Browse files Browse the repository at this point in the history
  • Loading branch information
Ankush1oo8 committed Mar 9, 2024
1 parent 7f77ad8 commit 6ed252b
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Heap/HeapSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package Heap;

public class HeapSort {
public static void heapify(int arr[],int i, int size){
int left=2*i+1;
int right = 2*i+2;
int maxIdx=i;

if(left<size && arr[left]>arr[maxIdx]){
maxIdx=left;
}
if(right<size && arr[right]>arr[maxIdx]){
maxIdx=right;
}
if(maxIdx !=i){
int temp=arr[i];
arr[i]=arr[maxIdx];
arr[maxIdx]=temp;

heapify(arr, maxIdx, size);
}
}
public static void heapsot(int arr[]){
int n=arr.length;
for(int i=n/2; i>=0; i--){
heapify(arr,i,n);
}

for(int i=n-1; i>0; i--){
int temp=arr[0];
arr[0]=arr[i];
arr[i]=temp;

heapify(arr,0,i);
}

}
public static void main(String[] args) {
int arr[]={1,2,4,5,3};
heapsot(arr);

for(int i=0; i<arr.length; i++){
System.out.println(arr[i]+" ");
}
System.out.println();
}
}

0 comments on commit 6ed252b

Please sign in to comment.