forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
HeapSort.java
50 lines (38 loc) · 1.32 KB
/
HeapSort.java
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
/*
* @author Marcelo Wischniowski <marcelowisc at gmail.com>
*/
public class HeapSort {
/**
* @param vetor Vetor que será ordenado
* Aplica a ordenação HeapSorte no vetor
*/
public int[] sort(int[] vetor) {
for (int i = vetor.length/ 2 - 1; i >= 0; i--){
heapify(vetor, vetor.length, i);
}
for (int i = vetor.length - 1; i>=0; i--)
{
int temp = vetor[0];
vetor[0] = vetor[i];
vetor[i] = temp;
heapify(vetor, i, 0);
}
return vetor;
}
void heapify(int arr[], int arrayLength, int rootElementIndex)
{
int leftIndex = 2*rootElementIndex + 1;
int rightIndex = 2*rootElementIndex + 2;
int largest = rootElementIndex;
if (leftIndex < arrayLength && arr[leftIndex] > arr[largest])
largest = leftIndex;
if (rightIndex < arrayLength && arr[rightIndex] > arr[largest])
largest = rightIndex;
if (largest != rootElementIndex){
int swap = arr[rootElementIndex];
arr[rootElementIndex] = arr[largest];
arr[largest] = swap;
heapify(arr, arrayLength, largest);
}
}
}