Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. // --- Directions
  2. // Implement bubbleSort, selectionSort, and mergeSort
  3.  
  4. function bubbleSort(arr) {
  5. // Implement bubblesort
  6. for (let i = 0; i < arr.length; i++) {
  7. for (let j = 0; j < arr.length - i - 1; j++) {
  8. if (arr[j] > arr[j + 1]) {
  9. const lesser = arr[j + 1];
  10. arr[j + 1] = arr[j];
  11. arr[j] = lesser;
  12. }
  13. }
  14. }
  15.  
  16. // return the sorted array
  17. return arr;
  18. }
  19.  
  20. function selectionSort(arr) {
  21. for (let i = 0; i < arr.length; i++) {
  22. let indexOfMin = i;
  23.  
  24. for (let j = i + 1; j < arr.length; j++) {
  25. if (arr[j] < arr[indexOfMin]) {
  26. indexOfMin = j;
  27. }
  28. }
  29.  
  30. if (indexOfMin !== i) {
  31. let lesser = arr[indexOfMin];
  32. arr[indexOfMin] = arr[i];
  33. arr[i] = lesser;
  34. }
  35. }
  36.  
  37. return arr;
  38. }
  39.  
  40. function mergeSort(arr) {
  41. if (arr.length === 1) {
  42. return arr;
  43. }
  44.  
  45. const center = Math.floor(arr.length / 2);
  46. const left = arr.slice(0, center);
  47. const right = arr.slice(center);
  48.  
  49. return merge(mergeSort(left), mergeSort(right));
  50. }
  51.  
  52. function merge(left, right) {
  53. const results = [];
  54.  
  55. while (left.length && right.length) {
  56. if (left[0] < right[0]) {
  57. results.push(left.shift());
  58. } else {
  59. results.push(right.shift());
  60. }
  61. }
  62.  
  63. return [...results, ...left, ...right];
  64. }
  65.  
  66. module.exports = { bubbleSort, selectionSort, mergeSort, merge };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement