-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7f77ad8
commit 6ed252b
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |