@@ -177,9 +177,54 @@ func swap(arr []int, i, j int) {
177
177
void QuickSort(int A[ ] , int low, int high) //快排母函数
178
178
{
179
179
if (low < high) {
180
- int pivot = Paritition1(A, low, high);
180
+ int pivot = Paritition1(A, low, high);
181
181
QuickSort(A, low, pivot - 1);
182
182
QuickSort(A, pivot + 1, high);
183
183
}
184
184
}
185
185
```
186
+
187
+ ## 7. Java 代码实现
188
+
189
+ ```java
190
+ public class QuickSort implements IArraySort {
191
+
192
+ @Override
193
+ public int[] sort(int[] sourceArray) throws Exception {
194
+ // 对 arr 进行拷贝,不改变参数内容
195
+ int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
196
+
197
+ return quickSort(arr, 0, arr.length - 1);
198
+ }
199
+
200
+ private int[] quickSort(int[] arr, int left, int right) {
201
+ if (left < right) {
202
+ int partitionIndex = partition(arr, left, right);
203
+ quickSort(arr, left, partitionIndex - 1);
204
+ quickSort(arr, partitionIndex + 1, right);
205
+ }
206
+ return arr;
207
+ }
208
+
209
+ private int partition(int[] arr, int left, int right) {
210
+ // 设定基准值(pivot)
211
+ int pivot = left;
212
+ int index = pivot + 1;
213
+ for (int i = index; i <= right; i++) {
214
+ if (arr[i] < arr[pivot]) {
215
+ swap(arr, i, index);
216
+ index++;
217
+ }
218
+ }
219
+ swap(arr, pivot, index - 1);
220
+ return index - 1;
221
+ }
222
+
223
+ private void swap(int[] arr, int i, int j) {
224
+ int temp = arr[i];
225
+ arr[i] = arr[j];
226
+ arr[j] = temp;
227
+ }
228
+
229
+ }
230
+ ```
0 commit comments