面试算法:快速排序

题目

快速排序是一种非常高效的算法,从其名字可以看出这种排序算法最大的特点就是快。当表现良好时,快速排序的速度比其他主要对手(如归并排序)快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;
        }
    }

}
相关推荐
多米Domi0118 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
罗湖老棍子8 小时前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim
方圆工作室8 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
Lips6118 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
kylezhao20199 小时前
C# 文件的输入与输出(I/O)详解
java·算法·c#
CodeByV10 小时前
【算法题】堆
算法
kaikaile199510 小时前
A星算法避开障碍物寻找最优路径(MATLAB实现)
数据结构·算法·matlab
今天_也很困10 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
企业对冲系统官10 小时前
基差风险管理系统日志分析功能的架构与实现
大数据·网络·数据库·算法·github·动态规划
ldccorpora10 小时前
GALE Phase 1 Chinese Broadcast News Parallel Text - Part 1数据集介绍,官网编号LDC2007T23
人工智能·深度学习·算法·机器学习·自然语言处理