Index & Sorting
Index
• Counting: when the index, or the position, is dependent on the item. Count from one. (Zero-based index is mathematically wrong.)
• Grid: when the index, or the position, is independent on the item. (e.g. JavaScript array)
Counting arrays are used in bubble sort, merge sort, quick sort, etc. Because of the nature of the index, sorting techniques using counting arrays require comparing the items and moving the items around.
Grid arrays are better suited for sorting.
Grid Sort
• Assigning the number (or other value associated with the number, such as name) to the corresponding index’s item
• Filtering out the undefined for print, iterate, length, etc.
• Assigning is sorting
• No comparing. No swapping. No moving around items.
• No need for indexOf()
• Stable
• Limitations : whole numbers only, size of an array
• An example using JavaScript
• https://code.sololearn.com/WWuuXR9rO45U/?ref=app
var test = [57, 285, 0, 854, 0, 27, 5, 5, 2885, 497, 57, 16, 803, 653, 62, 905, 975, 367, 147, 99, 58, 207643, 73, 83, 95, 24, 3, 1986, 47, 954, 1, 99, 954, 36, 67, 2, 753, 97, 3689, 79864, 5788, 479, 9865, 8900, 73, 753, 588, 19537, 489964, 30674, 578, 55, 99999, 578, 1000000, 58, 279, 3, 75, 975, 46, 785, 6789, 164, 5538, 744, 85, 2, 579, 753, 5538, 975, 158, 689, 379, 965, 57, 803, 84, 653, 85, 73, 864, 8643, 9047, 864, 783, 7, 4, 932, 5, 80, 97, 79, 849, 7, 3, 5, 10, 0]; document.write(test+”<br />”); document.write(“Count: “+test.length+”<br />”); document.write(“<br />”); var test_original = []; var x = 0; while (x < test.length){ if (test_original[test[x]] === undefined){ test_original[test[x]] = []; test_original[test[x]][0] = test[x]; } else{ test_original[test[x]].push(test[x]); } x = x + 1; } var test_defined = []; var defined_from = 0; var defined_to = test_original.length; var x = defined_from; while (x < defined_to){ if (test_original[x] !== undefined){ test_defined.push(x); } x = x + 1; } var definedIndex = 0; while (definedIndex < test_defined.length){ document.write(definedIndex + 1); document.write(“. “); document.write(test_defined[definedIndex]); document.write(“: “); document.write(test_original[test_defined[definedIndex]]); document.write(“<br />”); definedIndex = definedIndex + 1; }
test
variable with test input, then you copy it into a variable calledtest_original
in an odd manner.test_original
is not the original data, so where does the name come from?\$\endgroup\$test_original
. This can be a show stopper for large inputs. You mention "moving items around" as a problem of common sorting algorithms, however, this can be circumvented by sorting indices instead.\$\endgroup\$