1. 冒泡排序
package org.example;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
public class Sort {
@Test
public void testBubblingSort() {
int[] arr = {4, 5, 1, 44, 2, 5, 7};
bubblingSort(arr);
System.out.println(Arrays.toString(arr));
}
/**
* 冒泡排序
*
* @param arr
* @return
*/
public void bubblingSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
输出
[1, 2, 4, 5, 5, 7, 44]
2. 快速排序
package org.example;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
public class Sort {
@Test
public void testQuickSort() {
int[] arr = {4, 5, 1, 44, 2, 5, 7};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
/**
* 快速排序
*
* @param arr
* @param start
* @param end
*/
public void quickSort(int[] arr, int start, int end) {
if (start >= end) {
return;
}
int base = arr[start];
int i = start;
int j = end;
boolean fromTail = true;
while (i < j) {
if (fromTail) {
if (arr[j] < base) {
arr[i] = arr[j];
i++;
fromTail = false;
} else {
j--;
}
} else {
if (arr[i] > base) {
arr[j] = arr[i];
j--;
fromTail = true;
} else {
i++;
}
}
if (i == j) {
arr[i] = base;
break;
}
}
quickSort(arr, start, i - 1);
quickSort(arr, i + 1, end);
}
}
输出
[1, 2, 4, 5, 5, 7, 44]