How to Do Number Sorting in Java

You can use an array and a Java loop structure to sort a list of numbers. This method is called a "bubble" sort. Loop through each number, compare each number with the previous number, and swap the number location until you reach the end of the array. The result is a list of numbers in numerical order.

Instructions

    • 1

      Right-click the Java file you want to use to sort the numbers and click "Open With." Click your Java editor in the list of programs that appears.

    • 2

      Create an array variable of numbers. The following code creates an array of four numbers to sort using the bubble method:

      int[] numbers;
      numbers[0] = 5;
      numbers[1] = 3;
      numbers[2] = 6;
      numbers[3] = 1;

    • 3

      Loop through each number using the bubble method to sort the array. The following code sorts the array from least to greatest:

      for (int i = 0; i < numbers.length; i++) {
      int smallest = i;
      for (int j = i; j < numbers.length; j++) {
      if (numbers[j] < numbers[smallest])
      smallest= j;
      }
      int temp;
      temp = numbers[i];
      numbers[i] = numbers[smallest];
      numbers[smallest] = temp;
      }

Related Searches:

References

Comments

Related Ads

Featured