Skip to content

Commit

Permalink
Create 0912-sort-an-array.js
Browse files Browse the repository at this point in the history
Added solution for Sorting an array in JS.
  • Loading branch information
aadil42 authored Jun 7, 2023
1 parent 9d668c6 commit 671fffd
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions javascript/0912-sort-an-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* https://leetcode.com/problems/sort-an-array/
* Merge Sort
* Time O(n*log(n)) | Space O(n)
* @param {number[]} nums
* @return {number[]}
*/
var sortArray = function(nums) {

const merge = (left, mid, right) => {
const arr1 = nums.slice(left, mid+1);
const arr2 = nums.slice(mid+1, right + 1);

let p1 = 0;
let p2 = 0;
let gp = left;

while(p1 < arr1.length && p2 < arr2.length) {
if(arr1[p1] < arr2[p2]) {
nums[gp] = arr1[p1];
p1++;
} else {
nums[gp] = arr2[p2];
p2++;
}
gp++;
}

while(p1 < arr1.length) {
nums[gp] = arr1[p1];
p1++;
gp++;
}

while(p2 < arr2.length) {
nums[gp] = arr2[p2];
p2++;
gp++;
}
return nums;
}

const mergeSort = (left, right) => {

if(left === right) return nums;

const mid = Math.floor((left+right)/2);
mergeSort(left, mid);
mergeSort(mid+1, right);
return merge(left, mid, right);
}

return mergeSort(0, nums.length - 1);
};

0 comments on commit 671fffd

Please sign in to comment.