面试算法:快速排序

题目

快速排序是一种非常高效的算法,从其名字可以看出这种排序算法最大的特点就是快。当表现良好时,快速排序的速度比其他主要对手(如归并排序)快2~3倍。

分析

快速排序的基本思想是分治法,排序过程如下:在输入数组中随机选取一个元素作为中间值(pivot),然后对数组进行分区(partition),使所有比中间值小的数据移到数组的左边,所有比中间值大的数据移到数组的右边。接下来对中间值左右两侧的子数组用相同的步骤排序,直到子数组中只有一个数字为止。

题目

java 复制代码
public class Test {
    public static void main(String[] args) {
        int[] nums = {4, 1, 5, 3, 6, 2, 7, 8};
        int[] result = sortArray(nums);
        for (int item : result) {
            System.out.println(item);
        }
    }

    public static int[] sortArray(int[] nums) {
        quicksort(nums, 0, nums.length - 1);
        return nums;
    }

    public static void quicksort(int[] nums, int start, int end) {
        if (start < end) {
            int pivot = partition(nums, start, end);
            quicksort(nums, start, pivot - 1);
            quicksort(nums, pivot + 1, end);
        }
    }

    public static int partition(int[] nums, int start, int end) {
        int random = new Random().nextInt(end - start + 1) + start;
        swap(nums, random, end);

        int small = start - 1;// 把所有遇到的小元素全部放到头部
        for (int i = start; i < end; i++) {
            if (nums[i] < nums[end]) {
                small++;
                swap(nums, small, i);
            }
        }
        small++;
        swap(nums, small, end);

        return small;
    }

    private static void swap(int[] nums, int index1, int index2) {
        if (index1 != index2) {
            int temp = nums[index1];
            nums[index1] = nums[index2];
            nums[index2] = temp;
        }
    }

}
相关推荐
Nil20832 分钟前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
M78佐菲1 小时前
c语言学习笔记:排序与查找方法整理
linux·c语言·笔记·学习·算法
AI备案指南-满满3 小时前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
kyriewen4 小时前
面试官让我现场用 AI 改一个真实 bug——他打断我的 3 个理由
前端·面试·ai编程
土司大王5 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
众人皆醒我独醉5 小时前
流量路由:Istio 与 Knative 的集成
面试·kubernetes·llm
众人皆醒我独醉5 小时前
模型加载:storage-initializer 与节点级缓存
面试·kubernetes·gpu
大熊背6 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
吴声子夜歌6 小时前
Java面试——设计模式(一)
java·设计模式·面试