Reputation: 19
This is my first time posting to this blog. I'm new to Java and I have an issue with using bubble sort when a user inputs a set of values. Below is my code; however, I'm looking more for advice then an answer because I won't learn the language with the answer.
Thanks for your help and again sorry if my code is a little convoluted. BTW, I just started to learn Java so I won't be able to follow very complex coding advice.
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);
}
}
Upvotes: 1
Views: 9105
Reputation: 35
There are problems with your code.
System.out.println(list(n));//list(n)came out of nowhere
And you code seem to only sort out one of the array elements.
You can try this:
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] + " ");
}
}
Upvotes: 0
Reputation: 26185
Your code got a bit confused when you started referring to an undefined identifier list
.
I think you need:
System.out.println(Arrays.toString(numbers));
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
instead of:
System.out.println(list(n));
bubbleSort(n);
System.out.println(list(n));
n
is the number of input numbers, not something you would want to sort. numbers
contains the input data, and is a much more reasonable thing to sort.
Upvotes: 0