0

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;
           }
         }
      }
   }
}

2 Answers 2

1

Your bubbleSort method will sort the array in place, i.e. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.