1.冒泡排序
平均时间复杂度O(N2) 最好情况O(N)最坏情况O(N2) 空间复杂度O(1)
function bubbleSort(arr){ if(arr.length <= 1) return arr; var flag = 1; // 标识是否进行交换 for(var i=0; i < arr.length; i++){ if(i !=0 && flag) break; for(var j=0; j < arr.length-i-1; j++){ if(arr[j] > arr[j+1]){ if(flag == 1) flag = 0; var temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr; } var a = [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]; console.log(bubbleSort(a));
升级版冒泡排序
function bubbleSort2(arr) { var low = 0; var high= arr.length-1; //设置变量的初始值 var tmp,j; console.time(‘2.改进后冒泡排序耗时‘); while (low < high) { for (j= low; j< high; ++j) { //正向冒泡,找到最大者 if (arr[j]> arr[j+1]) { tmp = arr[j]; arr[j]=arr[j+1];arr[j+1]=tmp; } } --high; //修改high值, 前移一位 for (j=high; j>low; --j) { //反向冒泡,找到最小者 if (arr[j]<arr[j-1]) { tmp = arr[j]; arr[j]=arr[j-1];arr[j-1]=tmp; } } ++low; //修改low值,后移一位 } console.timeEnd(‘2.改进后冒泡排序耗时‘); return arr; } var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; console.log(bubbleSort2(arr));
2.选择排序
平均时间复杂度O(N2) 最好情况O(N2)最坏情况O(N2) 空间复杂度O(1) 适合小数据(1000以内)排序
function selectionSort(arr) { var len = arr.length; var minIndex, temp; console.time(‘选择排序耗时‘); 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; } console.timeEnd(‘选择排序耗时‘); return arr; } var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; console.log(selectionSort(arr));
3. 插入排序
平均时间复杂度O(N2) 最好情况O(N)最坏情况O(N2) 空间复杂度O(1)
function insertionSort(array) { console.time(‘插入排序耗时:‘); for (var i = 1; i < array.length; i++) { var key = array[i]; var j = i - 1; while ( array[j] > key) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } console.timeEnd(‘插入排序耗时:‘); return array; } var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; console.log(insertionSort(arr));
升级版(通过二分法查找左边有序数组中待差数字的插入位置)
function binaryInsertionSort(array) { console.time(‘二分插入排序耗时:‘); for (var i = 1; i < array.length; i++) { var key = array[i], left = 0, right = i - 1; while (left <= right) { var middle = parseInt((left + right) / 2); if (key < array[middle]) { right = middle - 1; } else { left = middle + 1; } } for (var j = i - 1; j >= left; j--) { array[j + 1] = array[j]; } array[left] = key; } console.timeEnd(‘二分插入排序耗时:‘); return array; } var arr=[3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; console.log(binaryInsertionSort(arr));
4. 快速排序
平均时间复杂度O(NlogN) 最好情况O(NlogN)最坏情况O(N2) 空间复杂度O(logN)
function quickSort(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)); } var arr=[2,3,1]; console.log(quickSort(arr));