归纳公式

选择排序 - 图1
**

转公式为代码

https://jsbin.com/jayojekabe/2/edit?js,console

  1. const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
  2. const _sortSelect = (a, start) => {
  3. if (start >= a.length - 1) return a;
  4. let min = a[start];
  5. let minIndex = start;
  6. for(let i = start + 1; i < a.length; i++) {
  7. if (a[i] < min) {
  8. min = a[i];
  9. minIndex = i;
  10. }
  11. }
  12. if (minIndex !== start) {
  13. swap(a, start, minIndex);
  14. }
  15. return _sortSelect(a, start + 1);
  16. }
  17. const sortSelect = (a) => _sortSelect(a, 0);
  18. console.log('------------', sortSelect([2, 1, 3, 1, 4]))
  19. console.log('--------', sortSelect([1,2,9,4,10,20,12]))
  20. // // [1, 2, 4, 9, 10, 12, 20]
  21. console.log('--------', sortSelect([11,2,39,24,1,2,9]))
  22. // // [1, 2, 2, 9, 11, 24, 39]
  23. console.log('--------', sortSelect([]))
  24. // // []
  25. console.log('--------', sortSelect([1,1,1,1,1]))
  26. const sortSelect2 = (a) => {
  27. for(let i = 0; i < a.length; i++) {
  28. let min = a[i];
  29. let minIndex = i;
  30. for(let j = i + 1; j < a.length; j ++) {
  31. if (a[j] < min) {
  32. min = a[j];
  33. minIndex = j;
  34. }
  35. }
  36. swap(a, i, minIndex);
  37. }
  38. return a;
  39. }
  40. console.log('------------', sortSelect2([2, 1, 3, 1, 4]))
  41. console.log('--------', sortSelect2([1,2,9,4,10,20,12]))
  42. // // // [1, 2, 4, 9, 10, 12, 20]
  43. console.log('--------', sortSelect2([11,2,39,24,1,2,9]))
  44. // // // [1, 2, 2, 9, 11, 24, 39]
  45. console.log('--------', sortSelect2([]))
  46. // // // []
  47. console.log('--------', sortSelect2([1,1,1,1,1]))