gpt4 book ai didi

java - 排序程序排序不正确

转载 作者:行者123 更新时间:2023-12-01 13:16:56 25 4
gpt4 key购买 nike

我的程序旨在以当前格式接收文件,其中顶部数字是单词的最大长度,第二个数字是存在的单词数,其余的数字是要排序的数字。

4
10
437 1807 3218 1791 9058 9322 766 9977 16 7143

然后从低到高排序。但每次我尝试让它工作时,我通常会在第一个位置得到最高的数字,其余的只是一团糟。最后三个 for 循环类似于以下伪代码:

 the first power of ten = 10;
for each i up to the maximum number of digits+1
1. for each value v in the array, starting at position 0:
a. isolate the “ith” digit from v (call this digit d) – use the current power
of ten to do this
b. add v to bin[d]
2. for each bin (that is, each bin[j], starting with j=0)
a. while bin[j] is not empty
i. remove the first value from bin[j] and copy it back into the next
position in the array
3. Increase the power of ten to the next power of ten

如有任何帮助,我们将不胜感激。

import java.io.*;
import java.util.*;
public class BinSort {

public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File(args[0]));
int length = sc.nextInt();
int size = sc.nextInt();
int[] temp = new int[size];
sc.nextLine();
for(int i = 0;i < temp.length;i++){
temp[i] = sc.nextInt();
}

sort(temp,size,length);
}

public static void sort(int[] input, int length,int size){
ArrayList<Integer>[]bin=(ArrayList<Integer>[]) new ArrayList[10];
for(int i = 0;i<length;i++){
bin[i] = new ArrayList<Integer>();
}

int power = 10;
for(int i = 0;i<size+1;i++){
for(int v = 0;v<input.length;v++){
int d = input[v] % power;
if(power>10)
d = d/ (power/10);
bin[d].add(input[v]);
}
for(int j = 0;j<10;j++){
while(!bin[j].isEmpty()){
int temp = bin[j].get(0);
bin[j].remove(0);
input[j] = temp;
}
}
power = power*10;

}
System.out.println("Final result");
System.out.println(Arrays.toString(input));
}
}

最佳答案

      input[j] = temp;

应该阅读

      input[pos] = temp;

关于java - 排序程序排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22394674/

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