gpt4 book ai didi

java - 计数排序/排序算法的变体

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:55:02 25 4
gpt4 key购买 nike

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

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]

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

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]]++;
}

}
}
}

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

最佳答案

编写一个合适的 Integer-Comparator 并使用 Arays.sort:

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);
}

}

}

编辑

让所有四位排在六位前面你可以做到(而不是排序两次)

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;
}

关于java - 计数排序/排序算法的变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39557402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com