简体   繁体   中英

Quick Sort Implementation - Python

I am trying to implement quick sort algorithm ( https://en.wikipedia.org/wiki/Quicksort ) in Python. I successfully implemented the algorithm in C++, but it is giving weird results in Python.

Here is the C++ code:

//Quicksort implementation
//Anchit Virmani - 27/10/2015 02:07 AM
#include <iostream>
using namespace std;

void swap(int* a, int* b)
{
    int t=*a;
    *a=*b;
    *b=t;
}

void quick_sort(int arr[],int l, int r)
{
    if(l<r)
    {
        int p=arr[l];
        int i=l+1;

        for(int j=(l+1);j<=r;j++)
        {
            if(arr[j]<p)
            {
                swap(&arr[j],&arr[i]);
                i++;
            }
        }
        swap(&arr[l],&arr[i-1]);

        quick_sort(arr,l,i-2);
        quick_sort(arr,i,r);

    }
}
int main() {
    int arr[3]={2,1,3};
    quick_sort(arr,0,2);

    for(int i=0;i<3;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

And this is the code I wrote in Python :

def quick_sort(arr,l,r):
    if(l<r):
        p=arr[l]
        i=l+1
        j=0

        for j in range(l+1,r+1):
            if arr[j]<p:
                arr[j],arr[i]=arr[i],arr[j]
                i=i+1


        arr[l],arr[r]=arr[r],arr[l]

        quick_sort(arr,l,i-2)
        quick_sort(arr,i,r)



arr=[4,3,2,1]
quick_sort(arr,0,3)

print(arr)

What is wrong with the Python implementation ?

Well, if you compare C++ and Python versions line by line you will notice that this line

 arr[l],arr[r]=arr[r],arr[l]

in Python differs from C++. Also your choice of pivot point seems weird.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM