给我写一个java排序算法
时间: 2024-05-27 19:10:36 浏览: 64
java排序算法
好的,以下是基于快速排序的Java排序算法示例代码:
public class QuickSort {
private int[] nums;
public QuickSort(int[] nums) {
this.nums = nums;
}
public void sort() {
quickSort(0, nums.length - 1);
}
private void quickSort(int left, int right) {
if (left >= right) return;
int pivotIndex = partition(left, right);
quickSort(left, pivotIndex - 1);
quickSort(pivotIndex + 1, right);
}
private int partition(int left, int right) {
int pivot = nums[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (nums[j] < pivot) {
i++;
swap(i, j);
}
}
swap(i + 1, right);
return i + 1;
}
private void swap(int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String[] args) {
int[] nums = { 5, 2, 9, 1, 5, 6 };
QuickSort qs = new QuickSort(nums);
qs.sort();
System.out.println(Arrays.toString(nums));
}
}
阅读全文