java常用排序算法

前言:

 

 

一、冒泡排序

1.1:基础冒泡排序

public class BubbleSort {
    public static void main(String[] args) {
        int[] ints = new int[]{23, 24,54,-324, 2, 1, 1, 98, 1};
        bubbleSort(ints);
        for (int anInt : ints) {
            System.out.print(anInt +" ");
        }
    }

    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            //冒泡次数
            //冒 泡步骤1
            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;
                }
            }
        }
    }
}

 

1.2:冒泡排序优化版

public class BubbleSort {
    public static void main(String[] args) {
        int[] ints = new int[]{23, 24,54,-324, 2, 1, 1, 98, 1};
        bubbleSort(ints);
        for (int anInt : ints) {
            System.out.print(anInt +" ");
        }
    }

    public static void bubbleSort(int[] arr) {

        Boolean flag = true;
        for (int i = 0; i < arr.length - 1; i++) {
            //冒泡次数
            //冒 泡步骤1
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {

                    // 如果数据经过移动表示,数组无序
                    flag = false;
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }

            // 如果数组是有序的则直接结束执行
            if (flag) {
                break;
            }
        }
    }
}

 

二:选择排序


public class SelectSort {

public static void main(String[] args) {

int[] ints = new int[]{23,24,54,-78,8,66,78,98,-56};
selectSort(ints);
for (int val: ints) {
System.out.println(val + " ");
}
}

public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int min = arr[i];
int minIndex = i;

// 查找最小值
for (int j = i+1; j < arr.length; j++) {
if (min > arr[j]) {
min = arr[j];
minIndex = j;
}
}

// 替换最小值
if (i != minIndex) {
arr[minIndex] = arr[i];
arr[i] = min;
}
}
}
}
 

 

三:插入排序

 

四:希尔排序

 

五:快速排序

六:归并排序

七:基数排序

 

posted @ 2022-12-28 21:13  银河系的极光  阅读(25)  评论(0)    收藏  举报