gpt4 book ai didi

Java 选择排序无法正常工作

转载 作者:行者123 更新时间:2023-12-01 10:46:25 24 4
gpt4 key购买 nike

我刚刚创建了一个名为“Statistics”的 int[ ] 类,它有两种选择排序方法,用于按升序或降序列出统计对象 (int[ ]) 中的整数。当我使用这两种方法中的任何一种时,它们往往在大约一半的时间内起作用,而在另一半的时间内不起作用。以下是我的意思的几个例子:

新运行

测试1 = {2, 5, 3, 7, 8, 9, 6}

Test1.sortDataDsc() 会给我:Test1 = {8, 7, 6, 9, 3, 5, 2}

测试 1A = {8, 7, 6, 9, 3, 5, 2}

Test1A.sortDataAsc() 会给我:{2, 5, 3, 6, 7, 8, 9}

新运行

测试1 = {2, 5, 3, 7, 8, 9, 6}

如果我首先执行 Test1.sortDataAsc() ,它将正确对数据进行排序,并且如果我之后执行此操作,也会正确地按降序对数据进行排序。

新运行

测试2 = {7, 4, 5, 8, 0, 1}

Test2.sortDataAsc() 会给我:{1, 0, 4, 5, 7, 8}。

然后,它会正确地按降序对这些数字进行排序,然后返回到正确的升序。

如果您以相同的顺序输入数字,我尝试过的所有测试用例都是可重复的。如果更改数字的顺序,则输出可能是正确的,也可能是不同的错误顺序。我已经排除了我能想到的所有可能导致此问题的问题,并且我找不到测试用例之间的任何相似之处。如果有人在我的代码中看到任何内容,我可以修复或添加以纠正这种情况,我将不胜感激。

count = 数组中元素的数量

//sortDataAsc Method - Sorts data elements in Statistics array from least to greatest
public void sortDataAsc(){
int min, temp;
for(int index = 0; index < count; index++){
min = index;
for(int scan = index + 1; scan < count; scan++){
if(data[scan] < data[min]){
min = scan;
}
temp = data[min];
data[min] = data[index];
data[index] = temp;
}
}
}

//sortDataDsc Method - Sorts data elements in Statistics array from greatest to least
public void sortDataDsc(){
int max, temp;
for(int index = 0; index < count; index++){
max = index;
for(int scan = index + 1; scan < count; scan++){
if(data[scan] > data[max]){
max = scan;
}
temp = data[max];
data[max] = data[index];
data[index] = temp;
}
}
}

最佳答案

尝试将您的代码更改为

//sortDataAsc Method - Sorts data elements in Statistics array from least to greatest
public void sortDataAsc(){
int min, temp;
for(int index = 0; index < count; index++){
min = index;
for(int scan = index + 1; scan < count; scan++){
if(data[scan] < data[min]){
min = scan;
}
} // closing parenthesis here
temp = data[min];
data[min] = data[index];
data[index] = temp;
}
}

//sortDataDsc Method - Sorts data elements in Statistics array from greatest to least
public void sortDataDsc(){
int max, temp;
for(int index = 0; index < count; index++){
max = index;
for(int scan = index + 1; scan < count; scan++){
if(data[scan] > data[max]){
max = scan;
}
} // closing parenthesis here
temp = data[max];
data[max] = data[index];
data[index] = temp;
}
}

附注对于升序排序,您可以使用

Arrays.sort(array);

以及降序排序

Integer[] arr = {2, 5, 3, 6, 1};
Arrays.sort(arr, Collections.reverseOrder());

关于Java 选择排序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34142099/

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