java - 数组排序与否?基础级 Java
问题描述
我正在尝试制作一个程序来告诉我我的数组是否已排序(升序和降序)。
我创建了一个函数,如果返回 true,则数组已经排序,如果返回 false,则数组未排序。
实际上,总是得到“未排序”。我不知道逻辑是否正确,但我认为是的,我不知道。
你们能帮帮我吗,伙计们?
package exercici11;
import java.util.Scanner;
public class SortedOrNot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
int prev1 = 0;
int prev2 = 0;
int cont1 = 0;
int cont2 = 0;
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < myArray.length; i++) {
myArray[i] = sc.nextInt();
}
String result = isSorted(myArray, prev1, prev2, cont1, cont2) ? result = "Is sorted." : "Is not sorted.";
System.out.println(result);
sc.close();
}
private static boolean isSorted(int[] myArray, int prev1, int prev2, int cont1, int cont2) {
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
prev1 = myArray[i];
if (prev1 < myArray[i]) {
// Ascending sort
cont1++;
if (cont1 == 10) {
return true;
}
} else if (prev2 > myArray[i]) {
// Descending sort
cont2++;
if (cont2 == 10) {
// Ascending sort
return true;
}
}
}
}
return false;
}
}
谢谢!
问候,亚历克斯。
解决方案
我改变了isSorted()
方法并添加了一些评论。
import java.util.Scanner;
public class SortedOrNot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < myArray.length; i++) {
myArray[i] = sc.nextInt();
}
String result = isSorted(myArray) ? result = "Is sorted." : "Is not sorted.";
System.out.println(result);
sc.close();
}
private static boolean isSorted(int[] myArray) {
int count = 0;
int firstElement = myArray[0];
int lastElement = myArray[myArray.length - 1];
if(lastElement - firstElement >= 0){
// Let's say myArray is sorted and if (lastElement - firstElement) >= 0
// then I check if the elements from array are in ascending order
// OR are all the same
for(int i = 0; i < myArray.length - 1; i++){
if(myArray[i] <= myArray[i + 1]) {
count++;
}
}
}
else {
// else I check if the elements from array are in descending order
for(int i = 0; i < myArray.length - 1; i++){
if(myArray[i] >= myArray[i + 1]){
count++;
}
}
}
// for n numbers there will be n - 1 comparisons
return count == myArray.length - 1;
}
}
推荐阅读
- assembly - 在汇编程序中调用外部 dll(逆向工程)
- javascript - 根据字符串中的时间进行数组排序
- javascript - 使用 AmCharts.makeChart V3 - 没有获得包括 POK 在内的新印度地图
- python - 使用python网格搜索的高斯过程回归hyparameter优化
- c++ - 为什么我们在重载 << 运算符而不是重载 = 和 + 运算符时通过引用返回对象?
- python - 使用 input() 函数从标准输入读取数组会引发 EOF 错误
- python - 将组标题数据移动到行中并删除标题行
- python-3.6 - 如何使用 mmap 在 python 中刷新页面数据
- linux - 如何阻止与在主机上的 docker 容器中创建的 IP 的连接
- javascript - 理解 React 中的 props 概念