Search code examples
javasortingbubble-sort

Bubblesort random Array Java


I'm very new to java and have been playing around with sorting algorithms. I have the following code working for a set array. I was just wondering what I'd need to change to get it to sort arrays of randoms lengths and integers. I guess the answer is pretty obvious any help is appreciated!

   public static void main(String[] args) {
   int number[]={8,5,3,2,9};

   int temp;
   boolean fixed=false;
   while(fixed==false){

       fixed=true;

   for(int i=0; i<number.length-1 ; i++){

       if(number[i] > number[i+1]){
       temp = number[i+1];
       number[i+1]=number[i];

       number[i]=temp;
       fixed=false;

       }

    }
   }
   for(int i=0; i<number.length; i++)
       System.out.println(number[i]);

    }

}

Solution

  • I mean, your algorithm would work regardless of the array's length. About how to generate such arrays, you could do this:

    int n = Math.random()*10000 + 1; //so its never 0.
    int number[] = new int[n];
    
    for(int i=0;i<n;i++) number[i]=Math.random()*10000;
    

    Everything else stays the same :).

    EDIT: You commented on the question that you'd rather generate the array by taking an input from the keyboard. You can do that by using a scanner.

    Scanner scanIn = new Scanner(System.in);
    
    do{
        int n = scanIn.nextInt();
    } while (n<1);
    
    int number[] = new int[n];   
    
    for(int i=0;i<n;i++) number[i] = scanIn.nextInt();
    
    scanIn.close();