-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
107 lines (88 loc) · 2.64 KB
/
QuickSort.java
File metadata and controls
107 lines (88 loc) · 2.64 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package java_core_basic;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class QuickSort {
public static void main(String[] args) throws IOException {
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader("data/input.txt");
bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
String[] tokens = line.split(" ");
int[] array = new int[0];
if (tokens.length == 1) {
ArrayList<Integer> list = new ArrayList<>();
list.add(Integer.parseInt(line.trim()));
while ((line = bufferedReader.readLine()) != null) {
list.add(Integer.parseInt(line.trim()));
}
array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
} else {
array = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
array[i] = Integer.parseInt(tokens[i]);
}
}
System.out.print("Đọc dữ liệu mảng đầu vào: " );
printArr(array);
System.out.print("\nMảng sau khi sắp xếp: " );
quickSort(array, 0, array.length - 1);
printArr(array);
} catch (FileNotFoundException ex) {
Logger.getLogger(QuickSort.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(QuickSort.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(QuickSort.class.getName()).log(Level.SEVERE, null, ex);
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(QuickSort.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return (i + 1);
}
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
public static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}