Quicksort 1 - Partition

Sort by

recency

|

401 Discussions

|

  • + 0 comments

    Java:

    public static List<Integer> quickSort(List<Integer> arr) {
        int pivot = arr.get(0);
        List<Integer> lArr = new ArrayList<>();
        List<Integer> rArr = new ArrayList<>();
        rArr.add(pivot);
        for (int j=1; j < arr.size(); j++) {
            if (arr.get(j) < pivot) {
                lArr.add(arr.get(j));
            } else {
                rArr.add(arr.get(j));
            }
        }
        lArr.addAll(rArr);
        return lArr;
    }
    
  • + 0 comments

    Here is problem solution in python java c++ c and javascript - https://programmingoneonone.com/hackerrank-quicksort-1-partition-problem-solution.html

  • + 0 comments

    vector quickSort(vector arr) { int i=0; int j=arr.size()-1; int p = arr[0]; while(i=arr[i])i++; while(p<=arr[j])j--; if(i

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/2HD41pYh8cU

    vector<int> quickSort(vector<int> arr) {
        vector<int> left, equal, right;
        for(int i = 0; i < arr.size(); i++){
            if(arr[i] < arr[0]) left.push_back(arr[i]);
            else if(arr[i] > arr[0]) right.push_back(arr[i]);
            else equal.push_back(arr[i]);
        }
        left.insert(left.end(), equal.begin(), equal.end());
        left.insert(left.end(), right.begin(), right.end());
        return left;
    }
    
  • + 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;
        }