public class TestSort {
public static void main(String[] args) {
int nums[] = { 7, 5, 3, 8, 4, 6, 1, 2 };
// bubbleSort(nums);
quickSort(nums, 0, nums.length - 1);
printNums(nums);
}
/**
* 冒泡排序
*/
public static void bubbleSort(int[] nums) {
int temp;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
/**
* 快速排序
*/
public static void quickSort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right, x = nums[left];
while (i < j) {
while (i < j) {
if (nums[j] < x) {
nums[i] = nums[j];
break;
}
j--;
}
if (i < j) {
i++;
}
while (i < j) {
if (nums[i] > x) {
nums[j] = nums[i];
break;
}
i++;
}
if (i < j) {
j--;
}
}
nums[i] = x;
quickSort(nums, left, i - 1);
quickSort(nums, i + 1, right);
}
public static void printNums(int[] nums) {
StringBuilder sb = new StringBuilder();
for (int num : nums) {
sb.append(num + ", ");
}
System.out.println(sb.toString());
}
}
冒泡排序,快速排序
最新推荐文章于 2022-08-02 10:08:39 发布