Repository navigation
Expand file tree
/
Copy path33-QuickSort.java
More file actions
47 lines (43 loc) · 1.42 KB
/
Copy path33-QuickSort.java
File metadata and controls
47 lines (43 loc) · 1.42 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
import java.util.Arrays;
import java.util.Scanner;
class QuickSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = readArray(scanner);
quickSort(numbers, 0, numbers.length - 1);
System.out.println("Sorted array: " + Arrays.toString(numbers));
scanner.close();
}
private static void quickSort(int[] numbers, int low, int high) {
if (low < high) {
int pivotIndex = partition(numbers, low, high);
quickSort(numbers, low, pivotIndex - 1);
quickSort(numbers, pivotIndex + 1, high);
}
}
private static int partition(int[] numbers, int low, int high) {
int pivot = numbers[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (numbers[j] <= pivot) {
i++;
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
int temp = numbers[i + 1];
numbers[i + 1] = numbers[high];
numbers[high] = temp;
return i + 1;
}
private static int[] readArray(Scanner scanner) {
System.out.print("Enter array size: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
return numbers;
}
}