Heap sort 7th heap sort exercises
For an int array, write a heap sort algorithm that sorts the array elements.
Given an int array a and the size of the array n, return the sorted array.
Test examples:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
Java (javac 1.7)Code Auto-Complete1
Import Java. util. *;
2
3
Public class Heapsort {
4
Public int Heapsort (intAintn) {
5
int LastIndex = N - 1;
6
Buildmaxheap (AlastIndex); //Build Maximum heap
7
while (lastIndex>0) {
8
Swap (A0lastIndex);
9
if (--lastIndex= =0) //Only one element left, you don't have to adjust the heap, the sort ends
10
break;
11
Adjustheap (A,0,lastIndex);
12
}
13
return A;
14
}
15
16
Public void Buildmaxheap (intarrintlastIndex) {
17
Adjust from the parent node of the last element to the end of the root node
18
int J = (lastIndex-1/2;
19
while (J>=0) {
20
int Rootindex = J;
21st
Adjustheap (arrrootindexlastIndex);
22
J --;
23
}
24
}
25
26
Public void Adjustheap (intarrintrootindexintlastIndex) {//start from the root node and adjust downwards
27
int Biggerindex = Rootindex;
28
int Leftchildindex = Rootindex * 2 + 1
29
int Rightchildindex = Rootindex * 2 + 2;
30
31
if (rightchildindex<=lastIndex) {//If the right child exists, the left child must exist
32
if (arr[rightchildindex>arr[rootindex| | arr [leftchildindex>arr[rootindex]) {
33
Assigns a larger element of the child node subscript to the Biggerindex
34
Biggerindex = arr [rightchildindex>arr[leftchildindex]? rightchildindex:leftchildindex;
35
}
36
}
37
Else if (leftchildindex<=lastIndex) {//guarantee that the left child exists and cannot cross the border
38
if (arr[leftchildindex>arr[rootindex]) {
39
Biggerindex = Leftchildindex;
40
}
41
}
42
if (biggerindex!=rootindex) {
43
Swap (arrbiggerindexrootindex);
44
Adjustheap (arrbiggerindexlastIndex);
45
}
46
47
}
48
49
Public void Swap (intarrintbiggerindexintrootindex) {
50
int Temp = arr [Rootindex];
51
arr [rootindex=arr[biggerindex];
52
arr [biggerindex=temp;
53
}
54
}
Your code is saved
The answer is right: Congratulations! The program you submitted passed all of the test cases
Algorithm-java code to implement heap sequencing