用java中的数组对2组分数进行排序
我编写了以下代码对两组分数进行排名:用java中的数组对2组分数进行排序,java,arrays,Java,Arrays,我编写了以下代码对两组分数进行排名: public class ScoreRanking { public static void main(String[] args) { int[] score1 = { 9, 3, 6, 19 }; int[] score2 = { 3, 3, 3, 3, 3, 5, 1 }; int[] rank1 = sortScores(score1); int[] rank2 = sor
public class ScoreRanking {
public static void main(String[] args) {
int[] score1 = { 9, 3, 6, 19 };
int[] score2 = { 3, 3, 3, 3, 3, 5, 1 };
int[] rank1 = sortScores(score1);
int[] rank2 = sortScores(score2);
for (int i = 0; i < rank1.length; i++) {
System.out.println((i + 1) + ": " + rank1[i]);
}
System.out.println("_________\n");
for (int j = 0; j < rank2.length; j++) {
System.out.println((j + 1) + ": " + rank2[j]);
}
}
static int[] sortScores(int[] sort) {
for (int i = 0; i < sort.length - 1; i++) {
if (sort[i] < sort[i + 1]) {
continue;
} else {
int temp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = temp;
}
}
return sort;
}
}
公共类分数排名{
公共静态void main(字符串[]args){
int[]score1={9,3,6,19};
int[]score2={3,3,3,3,5,1};
int[]rank1=sortScores(分数1);
int[]rank2=sortScores(分数2);
对于(int i=0;i
第一套已订购,但第二套未订购。我在括号里玩了一下,尝试了不同的顺序(分数1…分数1…分数2…分数2…分数2…/分数2…,分数2…分数1…分数1…),但是分数2总是被“忽略”。有人能告诉我为什么吗?我建议您按照dev8080的建议查找排序算法。您的排序算法只会遍历列表一次,这是闻所未闻的。虽然您的排序算法可能最终适用于第一个数组,但对于第二个数组,它存在问题:
if (sort[i] < sort[i + 1])
因为这是第一个值小于第二个值的唯一地方。这就是你得到结果的原因
1: 3
2: 3
3: 3
4: 3
5: 3
6: 1
7: 5
看起来您正在尝试实现冒泡排序的变体,在这种情况下,您应该查看以下链接:
请记住,对于较大的列表,冒泡排序不是非常有效我进行了一次冷调试,我认为您的问题在于sortScores方法。 如果我没有错的话,rank2数组的排序如下{3,3,3,3,1,5} 您面临的主要问题是,您的算法只更改了i和i+1元素,但当i+2元素低于i元素时,会发生什么情况,因此方法失败,无法正确执行任务 如果你想自己开发一个排序算法,我建议你首先在纸上用5或4个元素对数组进行排序,然后让他们试着理解你在做什么,他们用伪代码编写步骤,最后翻译成Java会更长,但我向你保证这会更令人满意,但是,如果你想对数组进行排序,现在就写它们,你应该检查维基百科上的排序算法,并特别关注这个数组,因为它易于理解,并且没有太多的复杂性 最后,如果您想使用java库来节省时间并对它们进行编码,那么应该检查sort(int[]a)方法 我希望我的回答能帮助你们更好地了解这个世界 再见,委内瑞拉的问候 警察局。插入排序算法如下所示:
public static void insertionSort (int[] array) {
for (int i=1; i < array.length; i++) {
int aux = array[i];
int j;
for (j=i-1; j >= 0 && array[j] > aux; j--){
array[j+1] = array[j];
}
array[j+1] = aux;
}
}
公共静态void insertionSort(int[]数组){
for(int i=1;i=0&&array[j]>aux;j--){
数组[j+1]=数组[j];
}
阵列[j+1]=aux;
}
}
Th错误符合逻辑。你的分类方法有缺陷。您应该查找排序算法。ignoredIt在控制台中显示为未排序是什么意思,即1:3、2:3、3:3、4:3、5:3、6:1、7:5无法在单个循环中对数组进行排序。
public static void insertionSort (int[] array) {
for (int i=1; i < array.length; i++) {
int aux = array[i];
int j;
for (j=i-1; j >= 0 && array[j] > aux; j--){
array[j+1] = array[j];
}
array[j+1] = aux;
}
}