首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计数排序/Sorting算法的变体

计数排序/Sorting算法的变体
EN

Stack Overflow用户
提问于 2016-09-18 11:56:56
回答 2查看 307关注 0票数 0

有一个问题给了我一个随机数作为一个枢轴,我必须将我的数组w.r.t排序到这个枢轴(最近先来,然后最远)。

代码语言:javascript
复制
array =[2,7,4,6,4,4,5,3,6,9,1,1,9] and 

    pivot=5 

    expected output: [5,4,4,6,6,3,7,2,1,1,9,9]

这有可能是计数排序的变化吗?如果不是!有人能给我一个解决这个问题的线索吗?在思考如何处理计数和数组索引时,我遇到了一个障碍,因此,到目前为止,我已经能够做到这一点。

代码语言:javascript
复制
class HelloEclipse{

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int N=sc.nextInt();
    int pivot=sc.nextInt();
    int[] mainArray=new int[N];
    int[] differenceArray=new int[N];
    int[] differnceCountArray=new int[Integer.MAX_VALUE];
    for(int i=0;i<N;i++){
        mainArray[i]=sc.nextInt();
        differenceArray[i]=pivot-mainArray[i];
        if(differenceArray[i]>0){
        differnceCountArray[differenceArray[i]]++;}
        else{
            differnceCountArray[-differenceArray[i]]++;
        }

    }
    }
}

任何关于如何进行的建议都是有帮助的!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-18 12:15:58

编写一个合适的整数比较器并使用Arays.sort:

代码语言:javascript
复制
public class PivotComparator implements Comparator<Integer> {

    private int pivot;

    public PivotComparator(int pivot) {
        super();
        this.pivot = pivot;
    }

    @Override
    public int compare(Integer a, Integer b) {
        return Math.abs(a - pivot) - Math.abs(b - pivot);
    }

    public static void main(String[] args) {

        Integer[] toSort = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        Comparator<Integer> comp = new PivotComparator(5);

        Arrays.sort(toSort, comp);
        for (Integer i : toSort) {
            System.out.println(i);
        }

    }

}

编辑

要把所有的四分放在六号前面,你可以做(而不是两次排序)。

代码语言:javascript
复制
public int compare(Integer a, Integer b) {
    int diff = Math.abs(a - pivot) - Math.abs(b - pivot);
    if (diff != 0) {
        return diff;
    }
    return a - b;
}
票数 2
EN

Stack Overflow用户

发布于 2016-09-18 12:21:14

下面是一个实现

代码语言:javascript
复制
    int[] array = { 2, 7, 4, 6, 4, 4, 5, 3, 6, 9, 1, 1, 9 };
    int pivot = 5;
    int[] sorted = Arrays.stream(array).boxed().sorted().sorted((i1, i2) -> Math.abs(i1 - pivot) - Math.abs(i2 - pivot)).mapToInt(i -> i).toArray();
    System.out.println(Arrays.toString(sorted));

输出

代码语言:javascript
复制
[5, 4, 4, 4, 6, 6, 3, 7, 2, 1, 1, 9, 9]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39557402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档