1.插入排序
1 let arr = [30, 5, 7, 60, 22, 18, 29] 2 let fn = arr => { 3 for (let j = 1; j < arr.length; j++) { 4 let current = arr[j] 5 let preIdx = j - 1 6 while (preIdx >= 0 && arr[preIdx] > current) { 7 arr[preIdx + 1] = arr[preIdx] 8 preIdx-- 9 } 10 arr[preIdx + 1] = current 11 } 12 return arr 13 } 14 console.log(fn(arr))
2·冒泡排序
1 let arr2 = [30, 18, 8, 10, 60, 24, 3] 2 let fn2 = arr => { 3 for (let i = 0; i < arr.length; i++) { 4 for (let j = 0; j < arr.length; j++) { 5 if (arr[j] > arr[j + 1]) { 6 let temp = arr[j + 1] 7 arr[j + 1] = arr[j] 8 arr[j] = temp 9 } 10 } 11 } 12 return arr 13 } 14 console.log(fn2(arr2), '冒泡')
3·选择排序
1 let arr3 = [30, 18, 8, 10, 60, 24, 3] 2 let minIdx = 0 3 let fn3 = arr => { 4 for (let i = 0; i < arr.length - 1; i++) { 5 minIdx = i 6 for (let j = i + 1; j < arr.length; j++) { 7 if (arr[j] < arr[minIdx]) { 8 minIdx = j 9 } 10 } 11 let temp = arr[i] 12 arr[i] = arr[minIdx] 13 arr[minIdx] = temp 14 } 15 return arr 16 } 17 console.log(fn3(arr3), '选择')
标签:10,arr,++,插入排序,冒泡排序,preIdx,let,排序,minIdx From: https://www.cnblogs.com/xingnizhiren/p/17480968.html