快速排序的递归形式和非递归形式

1.递归形式

int Quicksort(int arr[], int l, int r)
{
    if(l     {
        int l1=l,r1=r;
        int z=arr[l];
        while(l1         {
            while(arr[r1]>=z&&l1             arr[l1]=arr[r1];
            while(arr[l1]             arr[r1]=arr[l1];
        }
        arr[r1]=z;
        Quicksort(arr,l,r1-1);
        Quicksort(arr,r1+1,r);
    }
    return 0;
}

2.非递归版(栈模拟)

int Quicksort(int arr[],int n)
{
    st.push(0);
    st.push(n-1);
    while(!st.empty())
    {
        int r=st.top();
        int r1=r;
        st.pop();
        int l=st.top();
        int l1=l;
        st.pop();
        if(l         {
            int z=arr[l];
            while(l1             {
                while(arr[r1]>=z&&l1                     r1--;
                arr[l1]=arr[r1];
                while(arr[l1]                     l1++;
                arr[r1]=arr[l1];
            }
            arr[r1]=z;
            st.push(l);
            st.push(r1-1);
            st.push(r1+1);
            st.push(r);
        }
    }
    return 0;

}

你可能感兴趣的:(找工作)