1.冒泡:
// 时间复杂度o(n^2)
public class BubbleSort {
// bubble
public static void sort(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;
}
}
}
}
public static void main(String[] args) {
int[] arr = { 1, 10, 4, -1, 0 };
sort(arr);
for (int x : arr) {
System.out.println(x);
}
}
}
2.快排:
// 复杂度o(n)
public class QuickSort {
public static int partition(int[] arr, int low, int high) {
int temp = arr[low];
while (low < high) {
while (low < high && arr[high] > temp) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] < temp) {
low++;
}
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int middle = partition(arr, low, high);
sort(arr, low, middle - 1);
sort(arr, middle + 1, high);
}
}
public static void main(String[] args) {
int[] arr = { 0, -1, 9, 10, 5, 3, 6 };
sort(arr, 0, arr.length - 1);
for (int x : arr) {
System.out.println(x);
}
}
}