0

I want to do a bubble sort of numbers input by the user without asking the user how many numbers he wants to enter. User can enter as many numbers he can and the program should sort them all. So I want to find the number elements in the input before start sorting them. Here is the working code with user enter the array size himself

Update: it is one string of multiple integers eg "4 87 32 112 7" output I want is "4 7 32 87 112"(Ascending order)

import java.util.Scanner;
public class ArraySorting{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("Enter size of the array");
int z=in.nextInt();
int a[]=new int[z];
System.out.println("Enter numbers");
for(int i=0;i<z;i++){
a[i]=in.nextInt();
}
for(int j=0;j<z-1;j++){
for(int p=0;p<(z-1)-j;p++){
if(a[p]>a[p+1]){
int n=a[p];
a[p]=a[p+1];  
a[p+1]=n;
}//if loop
}//for loop 2
}//for loop 1
System.out.println("Numbers in Ascending order:");
for(int k=0;k<z;k++){
System.out.print(a[k]+" ");
}
}
}
Tom
  • 1
  • 1
  • 4
  • 3
    Possible duplicate of [Converting String to Int in Java?](http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java) – Guy Mar 04 '16 at 10:49
  • Does one `String` contains multiple numbers? Or just multiple digits which make up one number? – Martin Zabel Mar 04 '16 at 11:14
  • Can you format the code? – Sufian Mar 04 '16 at 11:33
  • 1
    Can you please explain better what you need? Explain what the user can enter, and where to go from there. Give some examples on what should happen in each situation so we can post a complete and accurate answer. – goncalopinto Mar 04 '16 at 11:38

1 Answers1

0

You can convert string sentence in to integer that can be Integer Value input for bubble sort.

import java.util.Scanner;

public class Sorting {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner reader = new Scanner(System.in);

    System.out.print("Enter the strings > ");
    String s1 = new String(reader.nextLine());

    String[] str = s1.split(" ");

    for(int i=1;i<str.length;i++){

        System.out.println(Integer.parseInt(str[i]));
    }
}

}

JDK
  • 83
  • 1
  • 12