Repository navigation
Expand file tree
/
Copy pathQuickSort.java
More file actions
78 lines (54 loc) · 1.95 KB
/
Copy pathQuickSort.java
File metadata and controls
78 lines (54 loc) · 1.95 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
package sort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr = new int[] {64, 72, 34, 87, 12, 11, 16, 88, 40, 70};
System.out.println(" " + Arrays.toString(arr));
quickSortAlg(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSortAlg(int[] arr, int from, int to) {
if (from < to) {
// делим примерно на пополам
int devideIndex = devideArray(arr, from, to);
// сортируем каждую часть
// внутри она тоже будет поделена попоплам
quickSortAlg(arr, from, devideIndex - 1);
System.out.println("");
quickSortAlg(arr, devideIndex, to);
}
}
public static int devideArray(int[] arr, int from, int to) {
int rightIndex = to;
int leftIndex = from;
int centerIndex = from + (to - from) / 2;
// примерно середина, берем значение этого элемента
int centerElem = arr[centerIndex];
while (leftIndex <= rightIndex) {
while (arr[leftIndex] < centerElem) {
leftIndex++;
}
while (arr[rightIndex] > centerElem) {
rightIndex--;
}
if (leftIndex <= rightIndex) {
changePositions(arr, rightIndex, leftIndex);
leftIndex++;
rightIndex--;
}
}
return leftIndex;
}
/**
* меняет местами элементы
*/
public static void changePositions(int[] arr, int from, int to) {
if (from == to) {
return;
}
int tmp = arr[to];
arr[to] = arr[from];
arr[from] = tmp;
System.out.println("шаг: " + Arrays.toString(arr));
}
}