var sort = (function () {
//快速排序
var quickSort = {
partition: function (array, low, high) {
if (low >= high) {
return;
}
var key = array[high];
var middle = low;
for (var i = low; i < high; i++) {
if (array[i] < key) {
if (i != middle) {
var tmp = array[middle];
array[middle] = array[i];
array[i] = tmp;
}
middle++;
}
} var tmp = array[high];
array[high] = array[middle];
array[middle] = tmp; return middle;
}, sort: function (array, low, high) { if (low < high) {
var middle = quickSort.partition(array, low, high);
quickSort.sort(array, low, middle - 1);
quickSort.sort(array, middle + 1, high);
}
}
}; //冒泡排序
bubbleSort = function (arr) {
var i = arr.length, j;
var temp;
while (i > 0) {
for (j = 0; j < i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
i--;
}
return arr; };
//插入排序
insertSort = function (array) {
if (!array) {
return;
} for (var i = 1; i < array.length; i++) { var tmp = array[i];
var j = i - 1; while (j>=0 && array[j]>tmp) {
array[j + 1] = array[j];
j--;
} array[j + 1] = tmp; } return array; };
return {
quickSort: quickSort.sort,
bubbleSort: bubbleSort,
insertSort:insertSort
}; })();
var array = [0, 2, 7, 4, 3, 5, 1, 6]; sort.quickSort(array, 0, array.length); sort.bubbleSort(array); alert(array.toString());