用 java语言以测试驱动开发实现快速排序
时间: 2023-11-06 12:46:38 浏览: 76
java实现快速排序
public class QuickSort {
public static void sort(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
quickSort(arr, 0, arr.length - 1);
}
private static void quickSort(int[] arr, int start, int end) {
if (start >= end) {
return;
}
int pivotIndex = partition(arr, start, end);
quickSort(arr, start, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, end);
}
private static int partition(int[] arr, int start, int end) {
int pivot = arr[end];
int left = start;
int right = end - 1;
while (left <= right) {
while (left <= right && arr[left] < pivot) {
left++;
}
while (left <= right && arr[right] >= pivot) {
right--;
}
if (left < right) {
swap(arr, left, right);
}
}
swap(arr, left, end);
return left;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
//测试
import org.junit.Test;
import static org.junit.Assert.*;
public class QuickSortTest {
@Test
public void testSort() {
int[] arr1 = null;
QuickSort.sort(arr1);
assertNull(arr1);
int[] arr2 = new int[]{};
QuickSort.sort(arr2);
assertArrayEquals(new int[]{}, arr2);
int[] arr3 = new int[]{1};
QuickSort.sort(arr3);
assertArrayEquals(new int[]{1}, arr3);
int[] arr4 = new int[]{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
QuickSort.sort(arr4);
assertArrayEquals(new int[]{1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9}, arr4);
}
}
阅读全文