samedi 6 octobre 2018

Java Arrays and Bubble Sort

I am trying to create a program that generates 10,000 random numbers, stores them in an array, and then uses the bubble method to sort them. Lastly, I want to print a list of 50 of these numbers unsorted and then sorted. I tried following the guide in my Java textbook, but I still cannot get the program to run. Any thoughts?

This is the program I am trying to run:

public static void main(String[] args)
   {
      // Initialize Array
      int [] values = new int[10000];
      Random randomNumbers = new Random();

      for(int element = 0; element < 50; element++)
      {
         values[element] = randomNumbers.nextInt(10000);
      }

      System.out.println("Original order: ");
      for(int element : values)
         System.out.print(element + "  ");

      IntBubbleSorter.bubbleSort(values);

      System.out.println("\nSorted order: ");
      for(int element: values)
         System.out.print(element + " ");

      System.out.println();
    }

And this is the class I am drawing from:

 public static void bubbleSort(int[] array)
   {
      int lastPost;
      int index;
      int temp;

      for(lastPost = array.length - 1; lastPost >= 0; lastPost--)
      {
         for(index = 0; index <= lastPost - 1; index++)
         {
            if(array[index] > array[index + 1])
            {
               temp = array[index];
               array[index] = array[index + 1];
               array[index + 1] = temp;
            }
          }
       }
    }




Aucun commentaire:

Enregistrer un commentaire