挑战程序设计竞赛(算法和数据结构)——7.2分割(上)JAVA实现

Posted 小乖乖的臭坏坏

tags:

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

题目:

思路:

示例1:

示例2:


代码如下:

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);//这个函数改变数组顺序!

        for (int i=0;i<n;i++){
            if (i==k){
                System.out.print("[" + A[i] + "] ");
            }
            else{
                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;
    }
}

输入:

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

输出:

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

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

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

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

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

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

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

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