how to implement quick sort algorithm in C++

前端 未结 4 1494
故里飘歌
故里飘歌 2021-02-06 12:28

here is the of quick sort algorithm from the MITOcw(Introduction To Algorithms ) lecture

QUICKSORT(A,p,q)
if(p < q)
then r = PARTITION(A,p,q)
     QUICKSORT         


        
4条回答
  •  长情又很酷
    2021-02-06 13:07

    This is a template based solution. However, it works only for arrays of elements for now. If anyone has an improvement to make it generic for both arrays and STL containers, please do so.

    template>
    void q_sort(T input[], int l_idx, int r_idx, compare comp = compare()) {
    
        if (l_idx >= r_idx)
            return;
    
        // The below is the partition block (can be made a sub function)
    
        int left = l_idx;
        int right = r_idx;
        {
            int pivot_idx = l_idx;
            T pivot = input[pivot_idx];
    
            while (left < right) {
                while (comp(input[left], pivot))
                    left++;
                while (comp(pivot, input[right]))
                    right--;
                swap(input[left], input[right]);
            }
    
            swap(pivot, input[left]);
        }
    
        q_sort(input, l_idx, left, comp);
        q_sort(input, left+1, r_idx, comp);
    
    }
    
    template>
    void quick_sort(T array[], int N, compare comp = compare()) {
        // This is an improvisation on the merge sort algorithm
        // is in-place and works on the divide-and-conquer methodology
        // Choose a pivot and find its appropriate place, such that
        // All elements less than the pivot are on its left and all elements
        // greater are on its right. Once found, split the porlblem into subsets
        // of elements less than and greater than the pivot and recursively
        // follow the process.
        q_sort(array, 0, N-1, comp);
    
    }
    
    int main()
    {
    
        int input[] = {11, 6, 3, 21, 9, 12};
        std::cout << "Before : ";
        for (int i=0; i < 6; i++)
            std::cout << input[i] << " ";
        std::cout << std::endl;
    
        quick_sort(input, 6);
        // or 
        //quick_sort(input, 6, std::greater());
    
        std::cout << "After : ";
        for (int i=0; i < 6; i++)
            std::cout << input[i] << " ";
        std::cout << std::endl;
    
    }
    

提交回复
热议问题