-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.java
80 lines (64 loc) · 1.92 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
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
package javaAlgorithms;
import java.util.Arrays;
import java.util.Random;
public class HeapSort {
//пирамидальная сортировка
private static int heapSize;
public static void sort (int [] a) {
buildHeap(a);
while (heapSize > 1) {
swap (a, 0, heapSize - 1);
heapSize--;
heapify (a, 0);
}
}
public static void buildHeap (int [] a) {
heapSize = a.length;
for (int i = a.length /2; i >= 0; i--) {
heapify(a, i);
}
}
public static void heapify (int [] a, int i) {
int l = left(i);
int r = right(i);
int largest = i;
if (l < heapSize && a[i] < a[l]) {
largest = l;
}
if (r < heapSize && a[largest] < a [r]) {
largest = r;
}
if (i != largest) {
swap (a, i, largest);
heapify(a, largest);
}
}
private static int right (int i) {
return 2* i + 2;
}
private static int left (int i) {
return 2 * i + 1;
}
private static void swap (int [] a, int i, int j) {
int temp = a [i];
a[i] = a[j];
a[j] = temp;
}
}
class Main {
public static void main(String[] args) {
long startTime = System.nanoTime();
int [] arr;
Random rand = new Random();
arr = new int [50];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(22);
}
System.out.println(Arrays.toString(arr));
HeapSort arrsort = new HeapSort();
arrsort.sort(arr);
System.out.println(Arrays.toString(arr));
long endTime = System.nanoTime();
System.out.println("На выполнение расчетов ушло " + (endTime - startTime) + " единиц времени");
}
}