Quicksort 1 - Partition

Sort by

recency

|

391 Discussions

|

  • + 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

    class Result {

    public static List<Integer> quickSort(List<Integer> arr) {
        int key = arr.get(0);
        int i = 0;
        for (int j = 1; j < arr.size(); j++) {
            if (arr.get(j) <= key) {
                i++;
                swap(arr, i, j);
            }
        }
        swap(arr, 0, i);
        return arr;
    }
    
    private static void swap(List<Integer> arr, int i, int j) {
        int temp = arr.get(i);
        arr.set(i, arr.get(j));
        arr.set(j, temp);
    }
    

    }

  • + 0 comments

    My C code solution

    int* quickSort(int arr_count, int* arr, int* result_count) {
        *result_count = arr_count;
        int j = 0,pivot = arr[0];
        int* ar = (int*)malloc(arr_count*sizeof(int));
        
        for(int i = 0;i < arr_count;i++){
            if(arr[i] < pivot){
                ar[j++] = arr[i];
            }
        }
        
        ar[j++] = pivot;
        for(int i = 0;i < arr_count;i++){
            if(arr[i] > pivot){
                ar[j++] = arr[i];
            }
        }
        return ar;
    }
    
  • + 0 comments

    python3:

        left = []
    right = []
    equal = [arr[0]]
    for i in range(1,len(arr)):
        if arr[i] > arr[0]:
            right.append(arr[i])
        else:
            left.append(arr[i])
    x = left + equal + right
    return x
    
  • + 0 comments

    The quicksort algorithm in Ruby

    def quickSort(arr)
        # Write your code here
        return arr if arr.length <= 1
    
        pivot = arr.delete_at(arr.length / 2)  # Select the pivot element
        left, right = arr.partition { |x| x < pivot }  # Partition the array
    
        # Recursively sort and combine
        return quickSort(left) + [pivot] + quickSort(right)
    
    end