Note that there are some explanatory texts on larger screens.

plurals
  1. POSelection algorithm returns wrong result sometimes
    primarykey
    data
    text
    <p>For a homework problem, I need to write a Java method to find the kth smallest number in an array, using quicksort-style partitioning. I was given the partition() method, and I'm supposed to write the method to get the kth smallest number.</p> <p>The problem asks that the pivot always be the rightmost element in the array range.</p> <p>I was given the following:</p> <pre><code>public int partition(int left, int right, long pivot) { int leftPtr = left - 1; int rightPtr = right + 1; while (true) { while (leftPtr &lt; right &amp;&amp; array[++leftPtr] &lt; pivot); while (rightPtr &gt; left &amp;&amp; array[--rightPtr] &gt; pivot); if (leftPtr &gt;= rightPtr) break; else swap(leftPtr, rightPtr); } return leftPtr; } </code></pre> <p>And I've written this method based on <a href="https://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_general_selection_algorithm" rel="nofollow">Wikipedia's pseudocode</a>:</p> <pre><code>public int kthSmallest(int left, int right, int k){ if(left &gt;= right){ return array[left]; } int pivotNewIndex = partition(left, right, array[right]); int pivotDist = pivotNewIndex - left - 1; if(pivotDist == k){ return array[pivotNewIndex]; } else if(k &lt; pivotNewIndex){ return kthSmallest(k, left, pivotNewIndex - 1); } else{ return kthSmallest(k - pivotDist, pivotNewIndex + 1, right); } } </code></pre> <p>But when I call <code>kthSmallest()</code> with randomly generated arrays of integers, about half the time it returns the wrong value. For example:</p> <pre><code>array: [45, 60, 24, 82, 87, 79, 16, 32, 59, 83, 20, 2, 1, 50, 11, 79, 72, 32, 0, 48, 69, 74, 22, 6, 96] expected result when k=4: 11 actual result when k=4: 87 </code></pre> <p>What am I doing wrong?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload