"Preliminary" exit from the do-when-when-when-when-wrapped fast-tracking area?



  • Have a good time of day and not judge strictly (less than a month studying C++).

    In a recurring algorithm, rapid grading has faced a problem. In cycle do{}while() There's a way out variables. r_p and l_p equal. The point is that the condition for the irration of the cycle (l_p<=r_p), then how can a way out if r_p==l_p?

    Code itself:

    #include <iostream>
    #include <stdlib.h>
    

    void quick_sort(int mas[],int left,int right);
    void swap(int &n1,int &n2);
    void printm(int mas[],int n);
    using namespace std;

    int main()
    {
    int mas1[5]={5,4,3,2,1};
    int mas2[5]={5,4,3,2,1};
    cout << "Quick Sort\n" << endl;
    cout<<"Before mas1: ";
    printm(mas1,5);
    quick_sort(mas1,0,4);
    cout<<"After mas1: ";
    printm(mas1,5);
    return 0;
    }
    void quick_sort(int mas[],int left,int right)
    {
    int l_p=left;
    int r_p=right;
    int pivot=(l_p+r_p)/2;
    do
    {
    while(mas[r_p]>pivot)
    r_p--;
    //cout<<r_p<<" ";
    while(mas[l_p]<pivot)
    l_p++;
    //cout<<l_p<<" ";
    if(l_p<=r_p)
    {
    cout<<"r_p="<<r_p<<" l_p="<<l_p<<"\n";
    cout<<"OK 1\n";
    swap(mas[l_p],mas[r_p]);
    r_p--;
    l_p++;
    cout<<"r_p="<<r_p<<" l_p="<<l_p<<"\n";
    }
    }while(l_p<=r_p); //<<-----------"Преждевременный" выход из цикла?
    //cout<<"OK 3 \n";
    if(left<r_p)
    quick_sort(mas,left,r_p);
    if(l_p<right)
    quick_sort(mas,l_p,right);
    }
    void swap(int &n1,int &n2)
    {
    cout<<"OK 2\n";
    int temp=n1;
    n1=n2;
    n2=temp;
    }
    void printm(int mas[],int n)
    {
    if(n<0)
    {
    cout<<"\nError! n must be >= 0.\n";
    exit(1);
    }
    else
    {
    for(int i=0;i<n;i++)
    {
    cout<<mas[i]<<", ";
    }
    cout<<"\n";
    }
    }



  • Was it sarcasm? If not, this code is present before the conclusion:

        while(mas[r_p]>pivot)
            r_p--;
        //cout<<r_p<<" ";
        while(mas[l_p]<pivot)
            l_p++;
        //cout<<l_p<<" ";
    

    which, with lungness, may change the values of variables which participate in the following condition:

     if(l_p<=r_p)
    

    prior to determination




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2