Guest User

Selection sort tests

a guest
May 20th, 2010
131
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Translation of Mike Taylor's selection sort unit tests from Ruby to JavaScript.
  2. // http://reprog.wordpress.com/2010/05/20/what-does-it-take-to-test-a-sorting-routine/
  3.  
  4. function arraysAreEqual(arr1, arr2) {
  5.     if (arr1.length !== arr2.length) {
  6.         return false;
  7.     } else {
  8.         for (var i = 0; i < arr1.length; i++) {
  9.             if (arr1[i] !== arr2[i]) {
  10.                 return false;
  11.             }
  12.         }
  13.     }
  14.  
  15.     return true;
  16. }
  17.  
  18. function numericComp(a, b) {
  19.     return (a < b ? -1 :
  20.             a > b ?  1 : 0);
  21. }
  22.  
  23. var output = (
  24.     console !== undefined && console.hasOwnProperty("log") ?
  25.     console.log :
  26.     function(msg) { alert(msg); }
  27. );
  28.  
  29. var tests = [
  30.     [],
  31.     [0],
  32.     [0, 0],
  33.     [0, 0, 0],
  34.     [0, 1],
  35.     [1, 0],
  36.     [0, 1, 2],
  37.     [0, 2, 1],
  38.     [1, 0, 2],
  39.     [1, 2, 0],
  40.     [2, 0, 1],
  41.     [2, 1, 0],
  42.     [0, 1, 1],
  43.     [1, 0, 1],
  44.     [1, 1, 0],
  45.     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  46.     [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
  47.     [42, 9, 17, 54, 602, -3, 54, 999, -11],
  48.     [-11, -3, 9, 17, 42, 54, 54, 602, 999],
  49.     [6, -Infinity, 7, -Number.MAX_VALUE, -3, 0, Infinity, 1, Number.MAX_VALUE, -26]
  50. ];
  51.  
  52. var random_tests = [];
  53. for (var i = 0; i < 10; i++) {
  54.     var a = [];
  55.     var size = Math.floor(Math.random() * 100);
  56.  
  57.     for (var j = 0; j < size; j++) {
  58.         a.push(Math.random() * 1000000-500000);
  59.     }
  60.  
  61.     random_tests.push(a);
  62. }
  63.  
  64. var ntests = 0;
  65. var nok = 0;
  66. var all_tests = tests.concat(random_tests);
  67.  
  68. for (var i = 0; i < all_tests.length; i++) {
  69.     var a = all_tests[i];
  70.     var copy = a.slice();
  71.     selectionSort(copy);
  72.  
  73.     if (arraysAreEqual(copy, a.sort(numericComp))) {
  74.         nok += 1;
  75.     } else {
  76.         output("failed test " + i + ": [" + a.join(' ') + "] -> [" + copy.join(' ') + "]");
  77.     }
  78.  
  79.     ntests += 1;
  80. }
  81. output("passed " + nok + " of " + ntests + " tests (" + 100*nok/ntests + "%)");
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×