I am attempting to randomly generate 10 numbers between 1 and 100, store them in an array, and then sort them using the bubble sort method included below. I am confident in the random number generation and storage, as well as the bubble sorting code. I am simply having an issue calling the bubbleSort method and printing the output. Please advise.
package chpt7_project;
import java.util.Arrays;
public class Chpt7_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Initialize array containing 10 numbers
int[] list = new int[10];
//Generate 10 random numbers in the range of 1 - 100
for(int i = 0; i < list.length; i++) {
list[i] = (int)(Math.random()*100 + 1);
} //End loop
//Print output
System.out.println("Generated unsorted list: " + Arrays.toString(list));
System.out.println("Bubble Sorted Numbers:" + Arrays.toString(bubbleSort(list)));
}
//BubbleSort method provided by textbook
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;
}
}
}
}
}
Your bubbleSort
method will sort the array in place, ie it will change the existing array. Also, it has a void
return type, so you cannot pass it as a parameter to Arrays.toString
.
I believe you need to replace this line:
System.out.println("Bubble Sorted Numbers:" + Arrays.toString(bubbleSort(list)));
with these two lines:
bubbleSort(list);
System.out.println("Bubble Sorted Numbers:" + Arrays.toString(list));
This way you sort the array first with a call to bubbleSort
, and then you pass the same list (which has now been modified by bubbleSort
) to Arrays.toString
.
Your bubblesort is of type void and does not return anything. try to change void to int[] and return your list.
therefore no value is passed inside your toString method.
Arrays.toString(bubbleSort(list)));
try doing something like this:
public static int[] 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;
}
}
}
return list;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.