三种排序
冒泡 选择 快速
public class MyClass {
public static void main(String[] args){
int[] arr = {3, 10, 38, 20, 23, 29,8};
bubbleSort(arr);//冒泡
selectSort(arr);//选择
quickSort(arr, 0, arr.length-1);//快速
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
private static void bubbleSort(int[] arr) {//从大到小
for (int i = 0; i < arr.length-1; i++) {
for(int j=0; j < arr.length-1-i; j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
private static void selectSort(int[] arr) {//选择排序
for (int i = 0; i < arr.length-1 ; i++) {
for(int j = i+1; j < arr.length; j++){
if(arr[i]>arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
public static void quickSort(int[] arr, int low, int high){//快排
int i,j, temp, t;
if(low>high){
return;
}
i = low;
j = high;
//temp就是基准位
temp = arr[low];
while (i < j){
//先看右边,依次往左递减
while (temp <= arr[j] && i <j){
j--;
}
//再看左边,依次往右递增
while (temp>=arr[i] && i < j){
i++;
}
//如果满足条件则交换
if(i < j){
t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
//最后将基准位 与 i 和 j相等位置的数字交换
arr[low] = arr[i];
arr[i] = temp;
//递归调用左半数组
quickSort(arr, low, j-1);
//递归调用右半数组
quickSort(arr, j+1, high);
}
}