一、冒泡排序
/** * [冒泡算法] * @param {[type]} ary [description] * 把最大往上冒 */ function BubbleSortArray(ary){ for (var i = 0, len = ary.length; i < len; i++) { for (var n = 0; n < len - i; n++) { if (ary[n] > ary[n + 1]) { var temp; temp = ary[n]; ary[n] = ary[n + 1]; ary[n + 1] = temp; } }; }; return ary; }
二、选择排序
/** * [选择排序] * @param {[type]} ary [description] * 每次选择最小的 */ function SelectSortArray (ary) { var min_index; for (var i = 0, len = ary.length; i < len - 1; i++) { min_index = i; for (var n = i + 1; n < len; n++) { if (ary[n] < ary[min_index]) { min_index = n; }; }; if (min_index != i) { var temp; temp = ary[i]; ary[i] = ary[min_index]; ary[min_index] = temp; }; }; return ary; }
三、插入排序
/** * [插入排序] * @param {[type]} ary [description] */ function InsertSortArray(ary){ for (var i = 1, len = ary.length; i < len; i++) {//因为第一个作为最初排序部分 var temp = ary[i]; var n = i - 1; while(n >= 0 && ary[n] > temp){ ary[n + 1] = ary[n]; n--; } ary[n + 1] = temp; }; return ary; }