File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Arrays ;
2+ import java .util .Scanner ;
3+
4+ /**
5+ * @author Dipyaman Saha (https://github.com/dipyamansaha) - HEAP SORT ALGORITHM -
6+ * https://en.wikipedia.org/wiki/Heapsort
7+ */
8+ public class HeapSortAlgo {
9+ static void HeapSort (int [] Arr ) {
10+ int n = Arr .length ;
11+
12+ BuildMaxHeap (Arr );
13+
14+ for (int i = (n - 1 ); i >= 0 ; i --) {
15+ int temp = Arr [0 ];
16+ Arr [0 ] = Arr [i ];
17+ Arr [i ] = temp ;
18+
19+ MaxHeapify (Arr , i , 0 );
20+ }
21+ }
22+
23+ static void MaxHeapify (int [] Arr , int n , int i ) {
24+ int l = (2 * i + 1 );
25+ int r = (2 * i + 2 );
26+
27+ int largest ;
28+
29+ if ((l < n ) && (Arr [l ] > Arr [i ])) largest = l ;
30+ else largest = i ;
31+
32+ if ((r < n ) && (Arr [r ] > Arr [largest ])) largest = r ;
33+
34+ if (largest != i ) {
35+ int temp = Arr [i ];
36+ Arr [i ] = Arr [largest ];
37+ Arr [largest ] = temp ;
38+
39+ MaxHeapify (Arr , n , largest );
40+ }
41+ }
42+
43+ static void BuildMaxHeap (int [] Arr ) {
44+ int n = Arr .length ;
45+
46+ for (int i = (n / 2 - 1 ); i >= 0 ; i --) MaxHeapify (Arr , n , i );
47+ }
48+
49+ public static void main (String [] args ) {
50+ System .out .println ("HEAP SORT ALGORITHM\n " );
51+
52+ Scanner sc = new Scanner (System .in );
53+
54+ System .out .print ("How many elements do you wanna insert? " );
55+ int n = sc .nextInt ();
56+
57+ int [] Arr = new int [n ];
58+
59+ System .out .println ("Enter the elements: " );
60+ for (int i = 0 ; i < n ; i ++) {
61+ Arr [i ] = sc .nextInt ();
62+ }
63+
64+ System .out .println ("The entered array: " + Arrays .toString (Arr ));
65+
66+ HeapSort (Arr );
67+ System .out .println ("The sorted array: " + Arrays .toString (Arr ));
68+ }
69+ }
You can’t perform that action at this time.
0 commit comments