title: Where am i going wrong with this "Select the kth smallest using partition?"
body: <pre><code>#include&lt;stdio.h&gt;
  #include&lt;conio.h&gt;
  
  #define P(x) printf("%d\n",x);
  int A[10];
  
  void printarray()
  {    
     for (int i = 0; i &lt; 8; i++)
         printf("%d ", A[i]);
  
      printf("\n");
  }
  
  void swap(int *x, int *y)
  {
      int temp = *x;
      *x = *y;
      *y = temp;
  }
  
  int partition(int beg, int end)
  {
     int a = beg, pivot = A[beg], b = end;
  
     while (a &lt; b)
     {
        while (A[a] &lt;=pivot) a++;
        while (A[b] &gt; pivot) b--;
        if (a &lt; b)
        {
            swap(&amp;A[a], &amp;A[b]);
            a++;
            b--;
        }
     }
     A[beg] = A[b];  // restore the pivot to its original location
     A[b] = pivot;
     return b; 
  }
  
  int Select(int start, int end, int key)
  {
      if (start == end)
          return A[start];
  
      int p = partition(start, end);
      int k = p - start + 1; // no of elements to the left of the pivot
  
      if (key &lt;= k)
          return Select(start, k, key);  // left
      else
          return Select(k+1, end, key-k);// right
    }
  }
  
  int main()
  {  
      // input being read from file
      freopen("inp.txt", "r", stdin);
  
      for (int i = 0; i &lt; 10; i++)
      {
          scanf("%d", &amp;A[i]);
      }
  
      P(A[Select(0, 7, 6)]);
      getch();
  
      return 0;
  }
  </code></pre>
  
  <p>Here I have used the partitioning function of the quick sort to partition the array. I am making recursive calls to either part of the partition based on the pivot being generated and the element that is being searched for.. i.e., the kth smallest element.</p>