經過比較兩個相鄰的項,(由小到大排序)若是第一個比的二個大,則交換它們的位置元素項向上移動至正確的順序,就好像氣泡升至表面,冒泡也所以得名。前端
const bubbleSort = (arr) => { const length= arr.length; for (let i = 0; i<length; i++){ //控制循環次數 for(let j = i; j<length-1; j++){ //進行迭代循環比較 if(arr[j] > arr[j+1]){ let swap = arr[j]; arr[j] = arr[j+1]; arr[j+1] = swap; } } } }
const bubbleSort = (arr) => { const length= arr.length; for (let i = 0; i<length; i++){ //控制循環次數 for(let j = i; j<length-1-i; j++){ //進行迭代循環比較足以-i if(arr[j] > arr[j+1]){ let swap = arr[j]; arr[j] = arr[j+1]; arr[j+1] = swap; } } } }
代碼實現:面試
function selectionSort(arr) { var length= arr.length; var minIndex; for (var i = 0; i < length - 1; i++) { minIndex = i; for (var j = i + 1; j < length; j++) { if (arr[j] < arr[minIndex]) { // 尋找最小的數 minIndex = j; // 將最小數的索引保存 } } if(i != minIndex){ var temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } return arr; }
代碼實現算法
function insertionSort(arr) { var len = arr.length; var preIndex, current; for (var i = 1; i < len; i++) { preIndex = i - 1; current = arr[i]; while(preIndex >= 0 && arr[preIndex] > current) { arr[preIndex+1] = arr[preIndex]; preIndex--; } arr[preIndex+1] = current; } return arr; }
function mergeSort(arr) { // 採用自上而下的遞歸方法,數組拆分 var len = arr.length; if(len < 2) { return arr; } var middle = Math.floor(len / 2), left = arr.slice(0, middle), right = arr.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; }
function quickSort(arr, left, right) { var len = arr.length, partitionIndex, left = typeof left != 'number' ? 0 : left, right = typeof right != 'number' ? len - 1 : right; if (left < right) { partitionIndex = partition(arr, left, right); quickSort(arr, left, partitionIndex-1); quickSort(arr, partitionIndex+1, right); } return arr; } function partition(arr, left ,right) { // 分區操做 var pivot = left, // 設定基準值(pivot) index = pivot + 1; for (var i = index; i <= right; i++) { if (arr[i] < arr[pivot]) { swap(arr, i, index); index++; } } swap(arr, pivot, index - 1); return index-1; } function swap(arr, i, j) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } function partition2(arr, low, high) { let pivot = arr[low]; while (low < high) { while (low < high && arr[high] > pivot) { --high; } arr[low] = arr[high]; while (low < high && arr[low] <= pivot) { ++low; } arr[high] = arr[low]; } arr[low] = pivot; return low; } function quickSort2(arr, low, high) { if (low < high) { let pivot = partition2(arr, low, high); quickSort2(arr, low, pivot - 1); quickSort2(arr, pivot + 1, high); } return arr; }
持續更新中~喜歡留下個贊哦!