[英]User input int to Array then use bubble sort to sort numbers
這是我第一次在這個博客上發帖。 我是 Java 新手,當用戶輸入一組值時,我遇到了使用冒泡排序的問題。 以下是我的代碼; 但是,我正在尋找更多的建議而不是答案,因為我不會通過答案學習語言。
感謝您的幫助,如果我的代碼有點復雜,再次抱歉。 順便說一句,我剛開始學習 Java,所以我無法遵循非常復雜的編碼建議。
import java.util.Arrays;
public class bubbleSort{
public static void main(String[] arg){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter total amount of numbers:" );
int n = input.nextInt();
int [] numbers = new int[n];
System.out.println("Enter the numbers: ");
for (int i = 0; i < n; i++) {
numbers[i] = input.nextInt();
}
System.out.println(list(n));
bubbleSort(n);
System.out.println(list(n));
}
public static void bubbleSort(int[] n){
boolean flag;
do{
flag = false;
for(int i = 0; i < n.length - 1; i++){
if (n[i] > n[i + 1]){
int temp = n[i];
n[i] = n[i + 1];
n[i + 1] = temp;
flag = true;
}
}
} while (flag);
}
}
當您開始引用未定義的標識符list
時,您的代碼有點混亂。
我認為你需要:
System.out.println(Arrays.toString(numbers));
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
代替:
System.out.println(list(n));
bubbleSort(n);
System.out.println(list(n));
n
是輸入數字的數量,而不是您想要排序的數字。 numbers
包含輸入數據,並且是更合理的排序方式。
你的代碼有問題。
System.out.println(list(n));//list(n)came out of nowhere
而且您的代碼似乎只整理出其中一個數組元素。
你可以試試這個:
public class BubbleSort {
public static void main(String[] args){
int[] myArray = new int[10];
for(int i = 0; i < myArray.length; i++){
myArray[i] = (int)(Math.random()* 100 + 1);
System.out.print(myArray[i] + " ");
}
System.out.println();
bubbleSort(myArray);
}
public static void bubbleSort(int[] array){
for(int i = 0; i < array.length - 1; i++){
for(int j = 0; j < array.length -1 - i; j++){
if(array[j] > array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.