0
0

常见排序算法(Java)

2024-09-24
2024-10-11
文章摘要
|
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;
    }
}

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或者给予支持!