解答
基本排序算法:冒泡,选择,插入,希尔,归并,快排
冒泡排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function bubbleSort(data){ var temp=0; for ( var i=data.length;i>0;i--){ for ( var j=0;j<i-1;j++){ if (data[j]>data[j+1]) { temp=data[j]; data[j]=data[j+1]; data[j+1]=temp; } } } return data; } |
选择排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function selectionSort(data){ for ( var i=0;i<data.length;i++){ var min=data[i]; var temp; var index=1; for ( var j=i+1;j<data.length;j++){ if (data[j]<min) { temp=data[j]; data[j]=min; min=temp; } } temp=data[i]; data[i]=min; data[index]=temp } } |
插入排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 | function insertSort(data){ var len=data.length; for ( var i=0;i<len;i++){ var key=data[i]; var j=i-1; while (j>=0&&data[j]>key){ data[j+1]=data[i]; j--; } data[j+1]=key; } return data; } |
希尔排序:
1 2 3 | function shallSort(array) { var increment = array.length; var i |
var temp; //暂存
do {
//设置增量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | increment = Math.floor(increment / 3) + 1; for (i = increment ; i < array.length; i++) { if ( array[i] < array[i - increment]) { temp = array[i]; for ( var j = i - increment; j >= 0 && temp < array[j]; j -= increment) { array[j + increment] = array[j]; } array[j + increment] = temp; } } } while (increment > 1) return array; } |
归并排序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | function mergeSort ( array ) { var len = array.length; if ( len < 2 ){ return array; } var middle = Math.floor(len / 2), left = array.slice(0, middle), right = array.slice(middle); return merge(mergeSort(left), mergeSort(right)); } function merge(left, right) { var result = []; while (left.length && right.length) { if (left[0] <= right[0]) { result.push(left.shift()); } else { result.push(right.shift()); } } while (left.length) result.push(left.shift()); while (right.length) result.push(right.shift()); return result; } |
快速排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function quickSort(arr){ if (arr.length==0) return []; var left=[]; var right=[]; var pivot=arr[0]; 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)); } |
这家笔试好难