-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathHeapSort.java
More file actions
executable file
·77 lines (61 loc) · 1.55 KB
/
HeapSort.java
File metadata and controls
executable file
·77 lines (61 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.Scanner;
public class HeapSort {
private static int N;
public static void sort(int array[]) {
max_heapify(array);
for (int i = N; i > 0; i--) {
swap(array, 0, i);
N = N - 1;
maxheap(array, 0);
}
}
public static void max_heapify(int array[]) {
N = array.length - 1;
for (int i = N / 2; i > 0; i--) {
// if ((2*i)>N)
// i=0;
maxheap(array, i);
}
}
public static void maxheap(int arr[], int i) {
int left = 2 * i;
int right = 2 * i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i) {
swap(arr, i, max);
maxheap(arr, max);
/*
* for (int j=0;j<arr.length;j++){ System.out.print(arr[j]); }
* maxheap(arr, max);
*/
}
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + "\n");
}
}
public static void swap(int array[], int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
System.out.print(" Sorted Element: " + array[j] + " " + array[i] + " ");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n, i;
System.out.println("Enter array size");
n = scan.nextInt();
int array[] = new int[n];
System.out.println("\nEnter numbers");
for (i = 0; i < n; i++)
array[i] = scan.nextInt();
sort(array);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
}
}