BUBBLE SORT

mail@pastecode.io avatar
unknown
plain_text
a year ago
4.0 kB
5
Indexable
Never
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bubblesort;

import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;

/**
 *
 * @author ADMIN
 */
public class BubbleSort {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int n = InputNumberArray();
        int[] array = RandomArray(n);
        PrintArray("The array:", array);
        bubbleSort(array);
        System.out.println();
        PrintArray("Sorted array : ", array);
    }

    public static int InputNumberArray() {
        Scanner scanner = new Scanner(System.in);
        int size;
        while (true) {  // Start an infinite loop to keep asking for input until a valid value is provided.
            try {
                System.out.println("Input Number of Array : ");
                size = Integer.parseInt(scanner.nextLine());  // Read the user's input and parse it as an integer.
                if (size > 0) {
                    break;
                    // if size > 0 , valid value and loop break 
                } else {
                    System.out.println("You have to input a positive number , Reinpiut : ");
                    // iff size <= 0 , Display notice 
                }
            } catch (NumberFormatException e) {
                System.out.println("Invalid value , Reinput : ");
                // if users input a special character , program will notice to users 
            }
        }
        return size;
    }

    public static int[] RandomArray(int ArraySize) {
        int[] array = new int[ArraySize];
        // Create a random object name random 
        Random random = new Random();
        for (int i = 0; i < ArraySize; i++) {
            array[i] = random.nextInt(ArraySize);
        } // loop use to random each element of array 
        return array;
    }

    public static void PrintArray(String variable, int[] array) {
        System.out.print(variable);
        System.out.print("[");
        // loop use to accessed each element of array and display them
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            if (i < array.length - 1) {
                System.out.print(",");
            }
        }// print each element of the array 
        System.out.print("]");
    }

   // compares two elements next to each other starting from the left and repeating continuously
    public static void bubbleSort(int[] arr) {
        // Get the length of the array.
        int n = arr.length;
        // A variable to check if there's any swapping in the current pass :  Biến kiểm tra xem có sự hoán đổi nào xảy ra trong lần duyệt hiện tại không.
        boolean swapped;
        for (int i = 0; i < n - 1; i++) { // Outer loop: Iterate through each element of the array.
            swapped = false; // Initially, assume there is no swapping in this pass.
            for (int j = 0; j < n - 1 - i; j++) { // Inner loop: Iterate through adjacent pairs and compare them.
                if (arr[j] > arr[j + 1]) { // Compare the current element with the next element.
                    // Hoán đổi arr[j] và arr[j + 1] neu can 
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true; // Mark that there was a swap in this pass. 
                }
            }
            // // If there was no swap in this pass, the array is already sorted.
            if (!swapped) {
                break;
            }
        }
    }

}