![](/img/trans.png)
[英]Sort an array such a way that First half should be in ascending order Second half should be in descending order in java
[英]When running code, sorting method prints same exact array numbers when the second array should be sorted in ascending or descending order
下面的代碼在selectionSorting
方法中,它只是一種特定的排序方式。 我認為問題出在此處,但我不確定如何解決。
if(orderAscending.isSelected()) {
boolean sorted = false;
int counting = arrayInt.length-1;
int errorCounter = 1;
int tempNum;
while(sorted == false) {
if(errorCounter == 0) {
sorted = true;
}else {
errorCounter = 0;
}
if(arrayInt[counting] < arrayInt[counting - 1] && sorted != true) {
tempNum = arrayInt[counting];
arrayInt[counting] = arrayInt[counting - 1];
arrayInt[counting - 1] = tempNum;
errorCounter++;
counting--;
}
if (counting == 0) {
counting = arrayInt.length-1;
}
}
String sOutput = "";
for(int i = 0; i < arrayInt.length-1; i++) {
sOutput = sOutput + arrayInt[i] + "\n";
}
sortedOutput.setText(sOutput);
Output
您的 while 循環應僅包含此代碼
if(orderAscending.isSelected()) {
boolean sorted = false;
int counting = arrayInt.length-1;
int errorCounter = 1;
int tempNum,secondLoop;
while(counting>0) {
secondLoop=0;
while(secondLoop<=counting){
if(arrayInt[counting] < arrayInt[secondLoop]) {
tempNum = arrayInt[counting];
arrayInt[counting] = arrayInt[secondLoop];
arrayInt[secondLoop] = tempNum;
}
secondLoop++;
}
counting--;
}
String sOutput = "";
for(int i = 0; i < arrayInt.length-1; i++) {
sOutput = sOutput + arrayInt[i] + "\n";
}
sortedOutput.setText(sOutput);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.