以下是一个使用Java编写的快速排序算法示例:

public class QuickSort {
    public static void sort(int[] arr, int low, int high) {
        if (arr == null || arr.length == 0)
            return;
        
        if (low >= high)
            return;
        
        int middle = low + (high - low) / 2;
        int pivot = arr[middle];
        
        int i = low, j = high;
        while (i <= j) {
            while (arr[i] < pivot) {
                i++;
            }
            
            while (arr[j] > pivot) {
                j--;
            }
            
            if (i <= j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }
        
        if (low < j)
            sort(arr, low, j);
        
        if (high > i)
            sort(arr, i, high);
    }
}

这是一个经典的快速排序算法,采用分治法的思想,先选取一个数作为pivot(一般是中间的数),然后将数组按照pivot分为两部分,左边的数都比pivot小,右边的数都比pivot大。

接着递归对左右两部分进行排序,最终得到一个有序数组。这个算法的时间复杂度为O(nlogn),是常用的排序算法之一。

Java 快速排序算法实现示例

原文地址: https://www.cveoy.top/t/topic/njW1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录