标签:工作 ber 包含 cat for merge nbsp 冒泡排序 调整
一、冒泡排序
遍历一个数组,如果发现数组中相邻的两个元素不满足要求时,就调整他们的次序,直达最后没有需要调整时说明数组有序。
function bubbleSort(arr = []) { arr = [].concat(arr); let len = arr.length, flags = false; for(let i = 0; i < len - 1; i++) { for(let j = 0; j < len - 1 - i; j++) { if(arr[j] > arr[j+1]) { let temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; flags = true; } } if(flags) { flags = false; } else { break; } }
return arr; }
二、选择排序
function selectSort(arr = []) { arr = [].concat(arr); let len = arr.length, minIndex, temp; for(let i = 0; i < len; i++) { minIndex = i; for(let 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; }
三、插入排序
function insertSort(arr = []) { arr = [].concat(arr); let len = arr.length, preIndex, current; for(let 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 shellSort(arr = []) { let len = arr.length; for(let gap = Math.floor(len / 2); gap > 0; gap = Math.floor(gap / 2)) { for(let i = gap; i < len; i++) { let j = i; let current = arr[i]; while(j - gap >= 0 && current < arr[j - gap]) { arr[j] = arr[j - gap]; j = j - gap; } arr[j] = current; } } return arr; }
五、归并排序
function mergeSort(arr = []) { let len = arr.length; if(len < 2) { return arr; } let middle = Math.floor(len / 2), left = arr.slice(0, middle), right = arr.slice(middle); return merge(mergeSort(left), mergeSort(right)) } function merge(left, right) { let result = []; while(left.length > 0 && right.length > 0) { 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.length); } return result; }
六、快速排序
function quickSort(arr, left, right) { let 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) { let pivot = left, index = pivot + 1; for(let 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) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
标签:工作 ber 包含 cat for merge nbsp 冒泡排序 调整
原文地址:https://www.cnblogs.com/iszhangjin/p/11676542.html