如何从main方法调用bubbleSort方法以打印排序列表数组。我已经在一个数组中生成了10个随机数,但我还没弄清楚如何调用bubbleSort并打印结果。我在这里错过了什么?
公共课Bubblesort {
public static void main(String [] args){
int [] numbers = new int[10];
//Generate 10 random numbers between 1-100
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random() * 100 + 1);
}//end of loop
System.out.println("The unsorted list is: " + Arrays.toString(numbers));
//Solution added
bubbleSort(numbers); //Call to sort the array
System.out.println("The sorted list is: " + Arrays.toString(numbers));
}
public static void bubbleSort(int[] list)
{
int temp;
for (int i = list.length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
if (list[j] > list[j + 1])
{
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
}
答案 0 :(得分:0)
你只是没有打电话给你的功能。
`public static void main(String [] args) { int [] numbers = new int [10];
//Generate 10 random numbers between 1-100
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random() * 100 + 1);
}//end of loop
bubblesort(numbers);
System.out.println("The unsorted list is: " + Arrays.toString(numbers));}
如您所见,我添加了 bubblesort(数字); ,它会调用您所做的功能。继续提问,因为我看到你是Java的新手,欢迎来到编码世界!
答案 1 :(得分:0)
import java.util.Arrays;
import java.util.Random;
public class BubbleSort{
static Random rand = new Random();
public static void main(String[] args) {
int [] numbers = new int[10];
//Generate 10 random numbers between 1-100
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(rand.nextFloat() * 100 + 1);
}//end of loop
System.out.println("The unsorted list is: " + Arrays.toString(numbers));
bubbleSort(numbers);
System.out.println("The sorted list is: " + Arrays.toString(numbers));
}
public static void bubbleSort(int[] list) {
int temp;
for (int i = list.length - 1; i > 0; i--){
for (int j = 0; j < i; j++){
if (list[j] > list[j + 1]){
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
}