九種排序演算法的js實現
摘要:
const arr = [44, 92, 82, 48, 2, 51];
/********* 1、氣泡排序 **********/
// 很常見很容易理解的排序演算法, 排序思路:遍歷陣列,每次遍歷就將最大(或最小)值推至最前。越往後遍歷查詢次數越少
const bubbleSort = ...
const arr = [44, 92, 82, 48, 2, 51]; /********* 1、氣泡排序 **********/ // 很常見很容易理解的排序演算法, 排序思路:遍歷陣列,每次遍歷就將最大(或最小)值推至最前。越往後遍歷查詢次數越少 const bubbleSort = arr => { const list = arr.slice(); //保證函式為純函式 const len = list.length; for (let i = 0; i < len; i++) { for (let j = len - 1; j > i; j--) { if (list[j] < list[j - 1]) { const tmp = list[j - 1]; list[j - 1] = list[j]; list[j] = tmp; } } } return list; } /********* 2、改進版氣泡排序 **********/ // 對上述氣泡排序的一種優化, 優化思路:當一次遍歷前後陣列不產生變化時,說明該陣列已經有序,結束排序。 const bubbleSort2 = arr => { const list = arr.slice(); //保證函式為純函式 const len = list.length; for (let i = 0; i < len; i++) { let exchange = false; for (let j = len - 1; j > i; j--) { if (list[j] < list[j - 1]) { const tmp = list[j - 1]; list[j - 1] = list[j]; list[j] = tmp; exchange = true; } } if (!exchange) return list } return list; } /********* 3、選擇排序 **********/ // 在無序區中選出最小的元素,然後將它和無序區的第一個元素交換位置。 const selectionSort = arr => { const list = arr.slice(); //保證函式為純函式 const len = list.length; for (let i = 0; i < len; i++) { let k = i for (let j = len - 1; j > i; j--) { if (list[j] < list[k]) k = j; } if (k !== i) { const tmp = list[k]; list[k] = list[i]; list[i] = tmp; } } return list; } /********* 4、插入排序 **********/ // 最普通的排序演算法, 從陣列下標1開始每增1項排序一次,越往後遍歷次數越多; const insertSort = arr => { const list = arr.slice(); //保證函式為純函式 const len = list.length; for (let i = 1; i < len; i++) { const tmp = list[i]; let j = i - 1; while (j >= 0 && tmp < list[j]) { list[j + 1] = list[j]; j--; } list[j + 1] = tmp; } return list; } /********* 5、快速排序 **********/ function quickSort(arr) { const list = arr.slice(); //為了保證這個函式是純函式,拷貝一次陣列 if (list.length <= 1) return list; const pivot = list.splice(0, 1)[0]; //選第一個作為基數 const left = []; const right = []; for (let i = 0, len = list.length; i < len; i++) { if (list[i] < pivot) { left.push(list[i]); } else { right.push(list[i]); } } return quickSort(left).concat([pivot], quickSort(right)) } 複製程式碼
2、效果圖

3、解答
- 如何在控制檯打印出上面圖片中的效果,eg:
const logStep = (i, leftArr, rightArr) => console.log(`%c 第${i}趟排序:%c ${arrStr(leftArr)}%c${arrStr(rightArr)} `, 'color:green', 'color:red', 'color:blue'); 複製程式碼
- 所有原始碼github地址: github.com/laifeipeng/…
- 彩色列印效果的github地址: github.com/laifeipeng/…