how to implement quick sort algorithm in C++

前端 未结 4 1485
故里飘歌
故里飘歌 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 12:54

    A much easier and clean implementation, also gives you number of minimum SWAPS in for QuickSort:

    int quickSort(int[], int, int);
    
    int partition(int[], int, int, int&);
    
    int main()
    {
        int array[] = {4, 2, 5};
        int size = sizeof(array)/sizeof(array[0]);
    
        /*
         first and last indices are passed
         idea is to move lower elements to the left of the list/pivot
         */
    
        int swaps = quickSort(array, 0, size-1);
    
        std::cout << "Minimum Swaps are: " << swaps << std::endl;
    
        for(int i = 0; i < size; i++)
        {
            std::cout << array[i] << " ";
        }
    }
    
    int quickSort(int array[], int start, int end)
    {
        int swaps = 0;
        if(start < end)
        {
            int pIndex = partition(array, start, end, swaps);
            //after each call one number(the PIVOT) will be at its final position
            swaps += quickSort(array, start, pIndex-1);
            swaps += quickSort(array, pIndex+1, end);
        }
        return swaps;
    }
    
    int partition(int array[], int start, int end, int& swaps)
    {
        int pivot = array[end];
        int pIndex = start;
    
        for(int i = start; i < end; i++)
        {
            if(array[i] <= pivot)
            {
    
                if(pIndex != i)
                {
                    std::swap(array[i], array[pIndex]);
                    swaps++;
                }
                pIndex++;
            }
        }
        if(pIndex != end)
        {
            std::swap(array[pIndex], array[end]);
            swaps++;
        }
        return pIndex;
    }
    

提交回复
热议问题