Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. Q: Write a function that takes a list of integers and returns the 4 highest in O(n) time.
  2.  
  3. A: Here, I use the merge sort algorithm since it uses O(n) space complexity and O(log(n)) runtime complexity. The following is my approach:
  4.  
  5. 1. First, divide the array into halves:
  6.  
  7. ```javascript
  8. arr = [1, 5, 6, 11, 3, 4, 8, 13];
  9.  
  10. const mergeSort = (arr) => {
  11. // end function when array consists of only one element
  12. if (arr.length === 1){
  13. return arr
  14. }
  15. // divide the array in half, taking into account the length of the array may be an odd number
  16. const middle = Math.floor(arr.length / 2);
  17. // create two arrays called left and right
  18. const left = arr.slice(0, middle);
  19. const right = arr.slice(middle, arr.length);
  20. // pass the two arrays into the merge helper function
  21. return merge(left, right)
  22. }
  23. ```
  24.  
  25. 2. Then, merge the individual arrays using a helper function merge algorithm:
  26.  
  27. ```javascript
  28. // O(n) algorithms have out of place complexity and need an extra array into which to sort the elements
  29. let result = [];
  30. let idxLeft = 0
  31. let idxRight = 0
  32.  
  33. // iterate over the left and right arrays as long as the index is less than the length of the array
  34. while (idxLeft < left.length && idxRight < right.length) {
  35.  
  36. // compare the elements in each array starting from index 0
  37. // if the number on the left is less than the number on the right
  38. if (left[idxLeft] <= right[idxRight]) {
  39. // push the left element into the result array
  40. result.push(left[idxLeft]);
  41. // increment the index
  42. idxLeft++
  43. } else {
  44. // otherwise, push the right element into the result array
  45. result.push(right[idxRight]);
  46. // increment the index (0 becomes 1, 1 becomes 2 ... )
  47. idxRight++
  48. }
  49. // in the result concatenate the sorted left and right arrays
  50. let mergedArr = result.concat(left.slice(idxLeft).concat(right.slice(idxRight)))
  51. // pass the newly merged array and number of items to return, into the helper function
  52. fourLargest(mergedArr, 4)
  53. }
  54. ```
  55.  
  56. 3. Finally, return the 4 largest elements in the now sorted and merged array:
  57.  
  58. ```javascript
  59. const fourLargest = (arr, n) => {
  60. // the slice method is used to return the four elements from the end of the sorted array
  61. let sliced = arr.slice(-n);
  62. console.log(sliced)
  63. }
  64. ```
  65.  
  66. 4. Don't forget to call the mergeSort function :-)
  67.  
  68. ```javascript
  69. // call the mergeSort function and pass in the array to be sorted
  70. mergeSort(arr)
  71. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement