title: Quick Select Algorithm
body: <p>Im trying to implement the Quick Select Algorithm on a Array that has randomly generated numbers. Now after writing the algorithm in code, it does not sort the array from lowest to highest nor am i able to find the kth smallest element. I would appreciate the help i get. Thank you.</p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;ctime&gt;
  #include&lt;cstdlib&gt;
  using namespace std;
  
  void printArray(int *myArray, int n){
      for(int i = 0; i &lt; n; i++){
         cout &lt;&lt; myArray[i] &lt;&lt; " ";
  }
  }
  
  int Partition(int *myArray, int startingIndex, int endingIndex){
  int pivot = myArray[endingIndex];
  int partitionIndex = startingIndex;
  for(int i = startingIndex; i&lt;endingIndex; i++){
      if(myArray[i]&lt;= pivot){
          swap(myArray[i],myArray[partitionIndex]);
          partitionIndex++;
      }
  }
  swap(myArray[partitionIndex],myArray[endingIndex]);
  return partitionIndex;
  } 
  
  int QuickSelect(int *myArray, int startingIndex, int endingIndex, int KthElement){
  /*if(startingIndex &lt; endingIndex){
      int partitionIndex = Partition(myArray, startingIndex,endingIndex);
      QuickSelect(myArray,startingIndex,partitionIndex-1);
      QuickSelect(myArray,partitionIndex+1,endingIndex);
  }*/1
  if (startingIndex &lt; endingIndex){
      int partitionIndex = Partition(myArray, startingIndex, endingIndex);
      if(KthElement == partitionIndex)
          return KthElement;
      if(KthElement &lt; partitionIndex)
          QuickSelect(myArray, startingIndex, partitionIndex - 1, KthElement);
      else
          QuickSelect(myArray, partitionIndex + 1, endingIndex, KthElement);
  }
  }
  int main(){
  
  int numOfElements;
  int KthElement;
  srand(time(NULL));
  cout&lt;&lt;"Enter The Amount Of Numbers You Wish To Use: ";
  cin &gt;&gt; numOfElements;
  int myArray[numOfElements];
  
  cout &lt;&lt; "Array Before Sorting: ";
  for(int i = 0; i&lt; numOfElements; i++){
      myArray[i] = rand() %10;
  }
  
  printArray(myArray, numOfElements);
  
  cout &lt;&lt; endl;
  cout &lt;&lt; endl;
  
  cout &lt;&lt;"Enter The Index Of The Kth Element You Wish To Retrieve: ";
  cin &gt;&gt; KthElement;
  
  QuickSelect(myArray, 0,numOfElements,KthElement);
  cout &lt;&lt; "Array After Sorting: ";
  printArray(myArray, numOfElements);
  cout &lt;&lt; endl;
  
  cout &lt;&lt;"The " &lt;&lt;KthElement&lt;&lt;" Smallest Element Is: " &lt;&lt;   QuickSelect(myArray,0,numOfElements,KthElement);
  
  }
  </code></pre>