Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
4.2 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 quicksort;

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

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

    /**
     * @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);
        quickSort(array, 0, array.length-1);
        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("]");
    }

    
    /* 
    Select an element as the "pivot", then split the array into two parts: 
    one part containing elements smaller than the pivot 
    and one part containing elements greater than the pivot. 
    Quick Sort is then called recursively on both parts of the array, until all elements have been sorted.
    */
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            // Find the pivot index and partition the array.
            int pivotIndex = partition(arr, low, high);

            // Recursively sort the two subarrays.
            quickSort(arr, low, pivotIndex - 1);   // Sort the left subarray.
            quickSort(arr, pivotIndex + 1, high);  // Sort the right subarray.
        }
    }

    // Partitioning function to find the pivot index.
    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];  // Choose the pivot as the last element.

        int i = low - 1;  // Index of the element smaller than the pivot.

        for (int j = low; j < high; j++) {
            if (arr[j] <= pivot) {
                i++;

                // Swap arr[i] and arr[j].
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // Swap arr[i + 1] and pivot.
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;  // Return the index of the pivot.
    }
}