简体   繁体   English

Java-如何根据单个int对数组进行排序

[英]Java - how to sort an array based off of single int

Say I have an array as such: 说我有这样一个数组:

[9, 7, 13, 24, 2, 16, 3, 10]

And I wanted to sort the array based off of the int 9, where all values less than 9 are to its left, and all values greater are to its right, could a version of selection sort be used? 我想根据int 9对数组进行排序,在int 9中,所有小于9的值都在其左侧,而所有较大的值都在其右侧,是否可以使用选择排序的版本?

A little stumped here 有点卡在这里

What you want should be something like one step of quick sort. 您想要的应该是一种快速排序的步骤。

I modify a little so that you can pass an pivot needed as a parameter : 我做了一些修改,以便您可以将所需的数据透视点作为参数传递:

public static void main(String[] args) {
    int[] a = new int[]{9,7,13,24,2,16,3,10};
    System.out.println(partition(a,9));//use value 9 as pivot 
    System.out.println(Arrays.toString(a));

}

private static int  partition(int[] a, int pivot){
    int pivotIndex = 0;

    for(int i=0;i<a.length;i++){//find initial pivot Index
        if(a[i]==pivot) {
            pivotIndex = i;
            break;
        }
    }


    int low = 0;
    int high = a.length-1;

    while(low<high){
        while(low<high&&a[high]>=pivot) high--;
        a[pivotIndex] = a[high];
        pivotIndex = high;

        while(low<high&&a[low]<=pivot) low++;
        a[pivotIndex] = a[low];
        pivotIndex= low;
    }

    //Actual pivotIndex finded
    a[pivotIndex] = pivot;

    return pivotIndex;
}

output: 输出:

3
[3, 7, 2, 9, 24, 16, 13, 10]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM