Skip to content

常见排序算法(Java)

java
public class Main {
    public static void main(String[] args) {
        int[] array = {5, 4, 3, 2, 1};
        bubbleSort(array);
        insertionSort(array);
        System.out.println(Arrays.toString(array));
    }
  
    /**
     * 冒泡排序
     */
    static void bubbleSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] > array[j]) {
                    swap(array, i, j);
                }
            }
        }
    }
  
    /**
     * 插入排序
     */
    static void insertionSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    swap(array, j, j + 1);
                }
            }
        }
    }
  
    static void swap(int[] array, int firstIndex, int secondIndex) {
        array[firstIndex] ^= array[secondIndex];
        array[secondIndex] ^= array[firstIndex];
        array[firstIndex] ^= array[secondIndex];
    }
  
    static void swapEasy(int[] array, int firstIndex, int secondIndex) {
        int temp = array[firstIndex];
        array[firstIndex] = array[secondIndex];
        array[secondIndex] = temp;
    }
}

最近更新:10/11/2024, 5:07:16 AM

原文链接:常见排序算法(Java)

|下一篇:element-plus form表单校验