Note that there are some explanatory texts on larger screens.

plurals
  1. POjavaScript quicksort not working when entries are >= 10
    primarykey
    data
    text
    <p>I have a table and I want to sort it by one field. However, I need to carry another field, which will provide the needed data for swapping the table entries. It works, but when the field that we sort by has a value 10 (maybe this will be a problem for entries >=10), it interprets 10 as 1, thus sorting results for the dataset 10 8 5 9 to 9 8 5 10. I can't figure out what's going on! Can you? :)</p> <p>SOLUTION (by Vache) The problem is that entries of array to be sorted are strings and not integers! I was collecting the entries of the array with jQuery and .text(). In addition I need to use parseInt() to convert string to an integer.</p> <pre><code>/** * Will swap two table entries * @param a - name of first player * @param b - name of second player */ function swapEntries(a, b) { var editor = $("#" + a); //put your ids here var viewer = $("#" + b); editorContent = editor.clone(); viewerContent = viewer.clone(); editor.replaceWith(viewerContent); viewer.replaceWith(editorContent); } /** * Will swap two array cells * @param ar - array * @param a - first cell's index * @param b - second cell's index */ function swap(ar, a, b) { var temp = ar[a]; ar[a] = ar[b]; ar[b] = temp; } /** * Quicksort. * @param a - The array to be sorted. * @param first - The start of the sequence to be sorted. * @param last - The end of the sequence to be sorted. * @param names - Array of names. */ function quickSort( a, first, last, names ) { var pivotElement; if(first &lt; last) { pivotElement = pivot(a, first, last, names); quickSort(a, first, pivotElement-1, names); quickSort(a, pivotElement+1, last, names); } } /** * Find and return the index of pivot element. * @param a - The array. * @param first - The start of the sequence. * @param last - The end of the sequence. * @param names - Array of names. * @return - the pivot element. */ function pivot( a, first, last) { var p = first; var pivotElement = a[first]; for(var i = first+1 ; i &lt;= last ; i++) { if(a[i] &gt; pivotElement) { p++; swap(a, i, p); swapEntries(names[i], names[p]); swap(names, i, p); } } swap(a, p, first); swapEntries(names[p], names[first]); swap(names, p, first); return p; } </code></pre>
    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