挑战程序设计竞赛(算法和数据结构)——分割(下)&快速排序的JAVA实现

Posted 小乖乖的臭坏坏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了挑战程序设计竞赛(算法和数据结构)——分割(下)&快速排序的JAVA实现相关的知识,希望对你有一定的参考价值。

在《挑战程序设计竞赛(算法和数据结构)——7.2分割(上)JAVA实现》中实现了将任一数组的元素以最后一个元素为界,小的排在前,大的排在后的功能,参照以下链接:

https://blog.csdn.net/weixin_42887138/article/details/121386199

接下来基于上述工作直接介绍快速排序:
思路:

图解:

java代码如下:

import java.io.BufferedInputStream;
import java.util.Scanner;

public class Partition 
    public static void main(String[] args) 
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        int n = cin.nextInt();
        int[] A = new int[n];
        for (int i=0;i<n;i++)
            A[i] = cin.nextInt();
        

        int k = partition2(A,0,n-1);//这个数返回加"[]"的下标,但是不改变数组顺序
        partition1(A,0,n-1);//这个函数改变数组顺序!

        System.out.println("分割的输出结果为:");
        for (int i=0;i<n;i++)
            if (i==k)
                System.out.print("[" + A[i] + "] ");
            
            else
                System.out.print(A[i] + " ");
            
        

        System.out.println("\\n快排的结果为:");
        quickSort(A, 0, n-1);
        for (int i=0;i<n;i++)
            System.out.print(A[i] + " ");
        
    

    public static void partition1(int[] A, int p, int r)
        int x = A[r];
        int i = p-1;
        for(int j = p;j<r;j++)
            if(A[j]<=x)
                i++;
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            
        
        int temp = A[i+1];
        A[i+1] = A[r];
        A[r] = temp;
    

    public static int partition2(int[] A, int p, int r)
        int x = A[r];
        int i = p-1;
        for(int j = p;j<r;j++)
            if(A[j]<=x)
                i++;
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            
        
        int temp = A[i+1];
        A[i+1] = A[r];
        A[r] = temp;
        return i+1;
    

    public static void quickSort(int[] A, int p, int r)
        if(p<r)
            int q = partition2(A, p, r);
            quickSort(A, p, q-1);
            quickSort(A, q+1, r);
        
    


输入:

12
13 19 9 5 12 8 7 4 21 2 6 11

输出:

快排的结果为:
2 4 5 6 7 8 9 11 12 13 19 21 

以上是关于挑战程序设计竞赛(算法和数据结构)——分割(下)&快速排序的JAVA实现的主要内容,如果未能解决你的问题,请参考以下文章

挑战程序设计竞赛(算法和数据结构)——19.1八皇后问题的JAVA实现

挑战程序设计竞赛(算法和数据结构)——15.5最小生成树(Kruskal算法)的JAVA实现

挑战程序设计竞赛(算法和数据结构)——19.2九宫格拼图问题的JAVA实现

挑战程序设计竞赛(算法和数据结构)——7.1归并排序JAVA实现

挑战程序设计竞赛(算法和数据结构)——16.13线段相交问题(曼哈顿算法)的JAVA实现

挑战程序设计竞赛(算法和数据结构)——3.6希尔排序的JAVA实现