Quicksort 1 - Partition

  • + 0 comments

    My Java solution with o(n) time complexity and o(n) space complexity:

    public static List<Integer> quickSort(List<Integer> arr) {
            if(arr.size() == 1) return arr; //already sorted
            
            int pivot = arr.get(0); // pivot is always arr[0]
            //declare each subarray
            List<Integer> left = new ArrayList<>();
            List<Integer> right = new ArrayList<>();
            List<Integer> equal = new ArrayList<>();
            
            //partition the og arr
            for(int element : arr){
                if(element < pivot) left.add(element);
                else if (element > pivot) right.add(element);
                else equal.add(element);
            }
            
            //combine the subarrays
            List<Integer> combinedList = 
                Stream.of(left, equal, right)
                .flatMap(List::stream)
                .collect(Collectors.toList());
            return combinedList;
        }