title: how to implement quick sort algorithm in C++
body: <p>here is the of quick sort algorithm  from the MITOcw(<a href="https://rads.stackoverflow.com/amzn/click/com/0262033844" rel="noreferrer" rel="nofollow noreferrer"><strong>Introduction To Algorithms</strong> </a>) lecture </p>
  
  <pre><code>QUICKSORT(A,p,q)
  if(p &lt; q)
  then r = PARTITION(A,p,q)
       QUICKSORT(A,p,r-1)
       QUICKSORT(A,r+1,q)
  
  PARTITION(A,p,q)
  x = A[p]
  i=p
  for j = p+1 to q
      if A[j] &lt;= x
         then i = i+1
              swap A[i] with A[j]
  swap A[p] with A[i]
  return i
  </code></pre>
  
  <p>and here its <strong>C++</strong> implementation on an integer array</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  void quickSort(int *,int,int);
  
  int partition(int *, int,int);
  
  int main()
  {
      int A[10]={6,10,13,5,8,3,2,25,4,11};
      int p=0,q=10;
  
      cout&lt;&lt;"======Original======="&lt;&lt;endl;
      for(int f=0; f&lt;10; f++)
          cout&lt;&lt;A[f]&lt;&lt;endl;
  
      quickSort(A,p,q);
  
      cout&lt;&lt;"======Sorted======="&lt;&lt;endl;
      for(int f=0; f&lt;10; f++)
          cout&lt;&lt;A[f]&lt;&lt;endl;
  }
  
  
  void quickSort(int *A, int p,int q)
  {
      int r;
      if(p&lt;q)
      {
          r=partition(A, p,q);
          quickSort(A,p,(r-1)); //I think the problem is here this first quickSort call
                                // is reducing the value of r and hence value of q becomes
                                // less than p recursively. How can I separate both calls
                                // one for left and one for right sub array of the pivot. 
          quickSort(A,(r+1),q);
      }
  }
  
  
  int partition(int *A, int p,int q)
  {
      int x= A[p];
      int i=p;
      int temp;
      int j;
  
      for(j=p+1; j&lt;q; j++)
      {
          if(A[j]&lt;=x)
          {
              i=i+1;
              temp= A[j];
              A[j]=A[i];
              A[i]=temp;
          }
  
      }
  
      temp= A[p];
      A[p]=A[i];
      A[i]=temp;
  
      return i;
  }
  </code></pre>
  
  <p>code doesn't yield sorted array although the first two runs of <strong>quickSort</strong> function gives desired output. that is it place the first pivot element to its correct position</p>