常见的内部排序算法有:插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序、基数排序等。
var quickSort = function(arr) {
if (arr.length <= 1) { return arr; }
var pivotIndex = Math.floor(arr.length / 2); //基准位置(理论上可任意选取)
var pivot = arr.splice(pivotIndex, 1)[0]; //基准数
var left = [];
var right = [];
for (var i = 0; i < arr.length; i++){
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right)); //链接左数组、基准数构成的数组、右数组
};
function selectionSort(arr) {
var len = arr.length;
var minIndex, temp;
for (var i = 0; i < len - 1; i++) {
minIndex = i;
for (var j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) { // 寻找最小的数
minIndex = j; // 将最小数的索引保存
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
var arr = [5,4,8,1,3,7,0,9,2,6];
var len = arr.length;
var tmp = null;
for(var j=0; j<len-1; j++){ //循环9次
for (var i=0; i<len-1-j; i++) { //每次比较10-j-1次数
if (arr[i]>arr[i+1]) {
tmp = arr[i+1];
arr[i+1] = arr[i];
arr[i] = tmp;
}
}
console.log('第'+(j+1)+'次循环',arr);<br> }
4.选择排序
var arr = [5,4,8,1,3,7,0,9,2,6];
var len = arr.length;
var min = null;
var tmp = null;
//选择排序
for(var j=0; j<len-1 ; j++){
min = j;
for(var i=j+1; i<len ;i++){
if(arr[i] < arr[min]){
min = i;
}
}
tmp = arr[j]
arr[j] = arr[min];
arr[min] = tmp;
console.log('第'+(j+1)+'次循环', arr);
}
function shellSort(arr) {
var len = arr.length,
temp,
gap = 1;
while(gap < len/3) { //动态定义间隔序列
gap = gap*3+1;
}
for (gap; gap > 0; gap = Math.floor(gap/3)) {
for (var i = gap; i < len; i++) {
temp = arr[i];
for (var j = i-gap; j >= 0 && arr[j] > temp; j -= gap) {
arr[j+gap] = arr[j];
}
arr[j+gap] = temp;
}
}
return arr;
}
var arr = [5,4,8,1,3,7,0,9,2,6];
var len = arr.length;
var cur = null;
var tmp = null;
//插入排序
for(var j=1; j<len ; j++){ //从第二个开始比较
cur = j-1;
tmp = arr[j]; //带插入元素
while (cur >= 0 && arr[cur] > tmp) {
arr[cur+1] = arr[cur];
cur--;
}
arr[cur+1] = tmp;
console.log('第'+(j)+'次循环', arr);
}
var arr = [5,4,8,1,3,7,0,9,2,6];
var merge_sort = function(v){
var merge = function(left, right){
var final = [];
while(left.length && right.length) {//两个数组的第一个值比较,并删除第一个值
final.push(left[0] <= right[0] ? left.shift() : right.shift());
}
console.log(final.concat(left.concat(right)));
return final.concat(left.concat(right));
}
//将数组分为2组
var len = v.length;
if (len < 2) return v;
var mid = len / 2;
return merge(
merge_sort(v.slice(0, parseInt(mid))),
merge_sort(v.slice(parseInt(mid)))
);
}
merge_sort(arr);