Ruby's Louvre

每天学习一点点算法

导航

计数排序

        var countSort = function(array) {
          var i, z = 0, count = [],
          min = Math.min.apply({}, array),
          max = Math.max.apply({}, array),
          size = array.length;
          //给新数组预填为零
          for (i = min; i <= max; i++) {
            count[i] = 0;
          }
          for (i=0; i < size; i++) {
            count[array[i]]++;
          }

          for (i = min; i <= max; i++) {
            while (count[i]-- > 0) {//循环新数组,如果不为零,则把i返回array
              array[z++] = i;
            }
          }
          return array;
        }

posted on 2010-01-20 18:33  司徒正美  阅读(860)  评论(0编辑  收藏  举报