class Main {
public static void main(String[] args) {
int[] nums = {3, 4, 6, 1, 2, 4, 7};
//quickSort(nums, 0, nums.length - 1);
selectionSort(nums);
//bubbleSort(nums);
Arrays.stream(nums).forEach(x -> System.out.println("x = " + x));
System.out.println();
}
//快排
static void quickSort(int nums[], int start, int end) {
if (start < end) {
int l = start;
int r = end;
int base = nums[l];
while (l < r) {
while (l < r && nums[r] < base) {
r--;
}
nums[l] = nums[r];
while (l < r && nums[l] > base) {
l++;
}
nums[r] = nums[l];
}
nums[l] = base;
quickSort(nums, start, l - 1);
quickSort(nums, l + 1, end);
}
}
static void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
boolean flag = true;
for (int j = 0; j < nums.length - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int t = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = t;
flag = false;
}
}
if (flag) {
break;
}
}
}
static void selectionSort(int[] nums) {
for (int i = 1; i < nums.length; i++) {
int minIndex = i - 1;
for (int j = i; j < nums.length; j++) {
if (nums[j] < nums[minIndex]) {
minIndex = j;
}
}
if (minIndex != i - 1) {
int t = nums[i - 1];
nums[i - 1] = nums[minIndex];
nums[minIndex] = t;
}
}
}
}
选择,冒泡,快排
最新推荐文章于 2025-03-06 10:06:52 发布
