Hackerrank - Quicksort 2 - Sorting

   

  • or less will be considered sorted, and there is no need to sort or to print them.

Note
Please maintain the original order of the elements in the left and right partitions while partitioning around a pivot element.

For example: Partition about the first element for the array A[]={5, 8, 1, 3, 7, 9, 2} will be {1, 3, 2, 5, 8, 7, 9}

Input Format
There will be two lines of input:

  • - the size of the array
    • - the n numbers of the array

    Output Format
    Print every partitioned sub-array on a new line.

    Constraints



    Each number is unique.

    Sample Input

    7
    5 8 1 3 7 9 2
    

    Sample Output

    2 3
    1 2 3
    7 8 9
    1 2 3 5 7 8 9
    

    Explanation
    This is a diagram of Quicksort operating on the sample array:

    quick-sort diagram

    Task
    The method quickSort takes in a parameter,

    , an unsorted array. Use the Quicksort algorithm to sort the entire array.


    import java.io.*;
    import java.util.*;

    public class Solution {
        
        public static ArrayList<Integer> quickSort(ArrayList<Integer> arr){
            ArrayList<Integer> res = new ArrayList<>();
            ArrayList<Integer> left = new ArrayList<>();
            ArrayList<Integer> right = new ArrayList<>();
            
            if (arr.size() == 1 || arr.size() == 0) {
                return arr;
            }
            
            int pivot = arr.get(0);
            
            for (Integer num : arr) {
                if (num < pivot) {
                    left.add(num);
                }else if(num > pivot)
                    right.add(num);
            }
            
            left = quickSort(left);
            right = quickSort(right);
            
            res.addAll(left);
            res.add(pivot);
            res.addAll(right);
            
            for (Integer num : res) {
                System.out.print(num+" ");
            }
            System.out.println();
            
            return res;
        }

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            ArrayList<Integer>  arr = new ArrayList<>();
            
            for (int i = 0; i < n; i++) {
                arr.add(sc.nextInt());
            }
            
            quickSort(arr);
            
            
        }
    }

    Comments

    Popular posts from this blog

    SPECIAL STRING ARRAY

    Code Goda 2022 - Special Numbers