diff --git a/DSA/Arrays/Insertionsort.js b/DSA/Arrays/Insertionsort.js new file mode 100644 index 0000000..6fdfe9d --- /dev/null +++ b/DSA/Arrays/Insertionsort.js @@ -0,0 +1,12 @@ +function insertionSort(arr) { + for (let i = 1; i < arr.length; i++) { + let currentValue = arr[i] + let j + for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { + arr[j + 1] = arr[j] + } + arr[j + 1] = currentValue + } + return arr +} +console.log(insertionSort([2, 1, 3, 7, 5])) // [1, 2, 3, 5, 7] \ No newline at end of file diff --git a/DSA/Arrays/Maximumsubarray.js b/DSA/Arrays/Maximumsubarray.js index fc2247e..f3a7a8b 100644 --- a/DSA/Arrays/Maximumsubarray.js +++ b/DSA/Arrays/Maximumsubarray.js @@ -1,12 +1,18 @@ -var maxSubArray = function(nums) { - var prev = 0; - var max = -Infinity; - - for (var i = 0; i < nums.length; i++) { - // Compare previous contiguous sum with current number - prev = Math.max(prev + nums[i], nums[i]); - // Check if the current prev is the greatest sum - max = Math.max(max, prev); - } - return max; -}; +const maxSubArray = (nums) => { + // initiate two variable, maxSum for total max, sum for current max + let maxSum = -Infinity + let currentSum = 0 + // iterate through the nums, store sub-problems result + for(let i = 0; i < nums.length; i++){ + //cumulating answers to the top + + //compare currentSum add current number + //with current number and store the maximum value + currentSum = Math.max(nums[i], currentSum + nums[i]) + + //compare maxSum with currentSum and store the greater value + maxSum = Math.max(currentSum, maxSum) + + } + return maxSum +} \ No newline at end of file