欢迎访问宙启技术站
智能推送

Java中的排序函数示例

发布时间:2023-12-03 08:09:22

Java中提供了多种排序算法的实现。下面会介绍一些常见的排序算法的示例代码。

1. 冒泡排序(Bubble Sort)

冒泡排序是一种简单的排序算法,它会多次遍历待排序的元素,每次比较相邻的两个元素,并根据需要交换位置。在每一次遍历中,最大(或最小)的元素会“浮”到序列的末尾,因此称为冒泡排序。

public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

2. 选择排序(Selection Sort)

选择排序是一种简单的排序算法,它每次从未排序的部分选择最小(或最大)的元素,然后将其放到已排序的部分末尾。选择排序的时间复杂度为O(n^2)。

public class SelectionSort {
    public static void selectionSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

3. 插入排序(Insertion Sort)

插入排序是一种简单直观的排序算法,它将未排序的元素逐个插入到已排序的部分中,直到所有元素都有序。插入排序的时间复杂度为O(n^2)。

public class InsertionSort {
    public static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; ++i) {
            int key = arr[i];
            int j = i - 1;

            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
}

4. 快速排序(Quick Sort)

快速排序是一种常用的排序算法,它采用递归的方式将问题分解为更小的子问题,并分别解决这些子问题。具体实现时,选择一个基准元素,将小于基准的元素放在左边,大于基准的元素放在右边,然后对左右两部分分别递归地进行快排。

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int partitionIndex = partition(arr, low, high);
            quickSort(arr, low, partitionIndex - 1);
            quickSort(arr, partitionIndex + 1, high);
        }
    }

    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;

                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }
}

以上仅是几种常见的排序算法的示例代码。在实际开发中,可以根据需要选择合适的排序算法,并使用Java提供的排序函数(如Arrays.sort())来简化代码的实现。