Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
3.6 kB
2
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 insertionsort;

import java.util.Random;
import java.util.Scanner;

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

    /**
     * @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);
        InsertionSort(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("]");
    }

    /*
    starting from the second element and comparing with the previous elements
    and inserting them at the correct position in the sorted section to make the sorted section always maintain ascending order.
     */
    public static void InsertionSort(int[] arr) {
        int n = arr.length;  // Get the length of the array.

        for (int i = 1; i < n; i++) {  // Start from the second element, assuming the first element is already sorted.
            int key = arr[i];  // Store the current element in 'key'.
            int j = i - 1;  // Initialize 'j' to the previous index.

            // Move elements of arr[0..i-1] that are greater than 'key' to one position ahead of their current position.
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];  // Shift the element to the right.
                j--;
            }

            arr[j + 1] = key;  // Place 'key' at the correct position in the sorted subarray.
        }
    }
}