forked from kapilkumar2001/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterative_heapsort.java
More file actions
92 lines (76 loc) · 1.64 KB
/
iterative_heapsort.java
File metadata and controls
92 lines (76 loc) · 1.64 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Java implementation of Iterative Heap Sort
public class HeapSort {
// function build Max Heap where value
// of each child is always smaller
// than value of their parent
static void buildMaxHeap(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
// if child is bigger than parent
if (arr[i] > arr[(i - 1) / 2])
{
int j = i;
// swap child and parent until
// parent is smaller
while (arr[j] > arr[(j - 1) / 2])
{
swap(arr, j, (j - 1) / 2);
j = (j - 1) / 2;
}
}
}
}
static void heapSort(int arr[], int n)
{
buildMaxHeap(arr, n);
for (int i = n - 1; i > 0; i--)
{
// swap value of first indexed
// with last indexed
swap(arr, 0, i);
// maintaining heap property
// after each swapping
int j = 0, index;
do
{
index = (2 * j + 1);
// if left child is smaller than
// right child point index variable
// to right child
if (index < (i - 1) && arr[index] < arr[index + 1])
index++;
// if parent is smaller than child
// then swapping parent with child
// having higher value
if (index < i && arr[j] < arr[index])
swap(arr, j, index);
j = index;
} while (index < i);
}
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i]=a[j];
a[j] = temp;
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {10, 20, 15, 17, 9, 21};
int n = arr.length;
System.out.print("Given array: ");
printArray(arr);
heapSort(arr, n);
System.out.print("Sorted array: ");
printArray(arr);
}
}