java bubble sort

java bubble sort

The "Bubble Sort" sorting algorithm is a simple sorting algorithm that works by comparing adjacent elements and swapping them position if they are in the wrong order. It is called "Bubble Sort" because the elements are compared and swapped as if they were floating like bubbles until the list is fully sorted.

Here is an example of how to implement the "Bubble Sort" sorting algorithm in Java:

refer t‮o‬:lautturi.com
public class BubbleSort {
  public static void main(String[] args) {
    // Creates an array of integers to be ordered
    int[] numbers = {5, 1, 7, 3, 8, 2, 9, 4, 6};

    // Uses the "Bubble Sort" algorithm to sort the array
    for (int i = 0; i < numbers.length - 1; i++) {
      for (int j = 0; j < numbers.length - i - 1; j++) {
        if (numbers[j] > numbers[j + 1]) {
          // Swaps position elements
          int temp = numbers[j];
          numbers[j] = numbers[j + 1];
          numbers[j + 1] = temp;
        }
      }
    }

    // Prints the ordered array
    for (int number : numbers) {
      System.out.print(number + " ");
    }
  }
}

This code will print the sequence of numbers "1 2 3 4 5 6 7 8 9".

Note that the "Bubble Sort" algorithm is an O(n^2) complexity ordering algorithm, which means that it is efficient for small lists, but is not ideal for very large lists because its performance worsens rapidly as the list size increases. If you need to sort large lists frequently, we recommend that you use a more efficient sorting algorithm, such as "Quick Sort" or "Merge Sort."

Created Time:2017-11-03 00:14:46  Author:lautturi