Java-массивы и сортировка по пузырькам - PullRequest
0 голосов
/ 07 октября 2018

ОБНОВЛЕНИЕ !!

Мне удалось заставить программу генерировать 50 случайных целых чисел (из 10000 случайных массивов int).Однако я изо всех сил стараюсь, чтобы метод пузырьковой сортировки сортировал полные значения (например, 4579 и 3457), а не только однозначные числа (3, 4, 4, 5, 5, 7, 7, 9)

Вот код, с которым я работаю:

public class RandomNumbers
{
   public static void main(String[] args)
   {
      int[] randomIntArray = new int[10000];

      for(int i = 0; i<randomIntArray.length; i++)
         randomIntArray[i] = (int)(Math.random() * 10000);

      for(int i = 0; i < 50; i++)
         System.out.println(randomIntArray[i]);

      System.out.println("Original order: ");
      for(int i = 0; i < 50; i++)
         System.out.print(randomIntArray[i] + "  ");

      IntBubbleSorter.bubbleSort(randomIntArray);

      System.out.println("\nSorted order: ");
      for(int i = 0; i < 50; i++)
         System.out.print(randomIntArray[i] + " ");

      System.out.println();
   }

}

и

public class IntBubbleSorter {
   public static void bubbleSort (int[] randomIntArray) {
      int lastPost;
      int index;
      int temp;

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

Мой текущий вывод выглядит следующим образом (для удобства чтения укорочено до 5 целых чисел):

Original order: 3898  6015  462  1960  8040
Sorted order: 0 1 2 2 3

Ответы [ 2 ]

0 голосов
/ 07 октября 2018

Если ваши основные функции и функции bubbleSort находятся в разных классах, убедитесь, что они находятся в одном пакете (папке).

randomNumbers.nextInt(10000)

означает, что следующее случайное число должно быть в диапазоне от 0 до 10000, и вытолько генерирует 50 случайных чисел.

Я создал два класса, один для основной функции, а другой для пузырьковой сортировки.Вы должны изменить их на те, которые вам подходят, но убедитесь, что они находятся в одной папке (в одном пакете)

MainClass:

import java.util.Random;

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

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

        System.out.println("Original order: ");
        for(int index = 0; index < 50; index++)
        {
            System.out.print(values[index] + "  ");
        }

        IntBubbleSorter.bubbleSort(values);

        System.out.println("\nSorted order: ");

        for(int index = 0; index < 50; index++)
        {
            System.out.print(values[index] + "  ");
        }

        System.out.println();
    }
}

Класс IntBubbleSorter:

public class IntBubbleSorter {
    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;
                }
            }
        }
    }
}
0 голосов
/ 07 октября 2018

прежде всего в главной функции в этом цикле:

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

вы создаете только 50 случайных чисел в вашем массиве 10000, а другое число в массиве присваивает 0 по умолчанию.

секунда: попробуйте вместо этой строки: IntBubbleSorter.bubbleSort(values); этой строки: bubbleSort(values);

...