-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhomeworkQuickSort.java
More file actions
54 lines (35 loc) · 1.32 KB
/
homeworkQuickSort.java
File metadata and controls
54 lines (35 loc) · 1.32 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
package treino;
import java.util.Arrays;
public class homeworkQuickSort {
public static void main(String[] args) {
int [] arr = {8, 7, 6, 5, 4, 3, 2, 1};
int[] sortedArr = quickSort(arr);
System.out.println(Arrays.toString(sortedArr));
}
public static int[] quickSort(int[] arr) {
if (arr.length <= 1) {
return arr;
}
int baseElement = arr[arr.length - 1];
int index = 0;
int temp;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] < baseElement) {
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
index++;
}
}
temp = arr[arr.length - 1];
arr[arr.length - 1] = arr[index];
arr[index] = temp;
int[] leftPart = quickSort(Arrays.copyOfRange(arr, 0, index));
int[] rightPart = quickSort(Arrays.copyOfRange(arr, index + 1, arr.length));
int[] result = new int[arr.length];
System.arraycopy(leftPart, 0, result, 0, leftPart.length);
result[index] = baseElement;
System.arraycopy(rightPart, 0, result, index + 1, rightPart.length);
return result;
}
}