Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active April 30, 2023 20:16
Show Gist options
  • Select an option

  • Save anushshukla/384b2b57fdd787eaf5e875a1043fca84 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/384b2b57fdd787eaf5e875a1043fca84 to your computer and use it in GitHub Desktop.
Sorting implementation (Typescript)
const isBothArraySame = (a: any[], b: any[]) => !!a && !!b && !(a < b || b < a);
const mergeSort = (nums: number[]): number[] => {
if (nums.length < 2) {
return nums;
}
if (nums.length === 2) {
const currentNum = nums[0];
const nextNum = nums[1];
return currentNum <= nextNum ? [currentNum, nextNum] : [nextNum, currentNum];
}
const middleIndex = Math.ceil(nums.length / 2);
const firstHalf = nums.splice(0, middleIndex);
const secondHalf = nums.splice(-middleIndex);
const firstHalfSort = mergeSort(firstHalf);
const secondHalfSort = mergeSort(secondHalf);
if (secondHalfSort.at(-1) < firstHalfSort[0]) {
return secondHalfSort.concat(firstHalfSort)
}
if (firstHalfSort.at(-1) < secondHalfSort[0]) {
return firstHalfSort.concat(secondHalfSort)
}
const sortedArr = [] as number[];
console.log({ firstHalfSort, secondHalfSort });
firstHalfSort.forEach(firstHalfSortNum => {
let index = 0;
while (index < secondHalfSort.length) {
const secondHalfSortNum = secondHalfSort[index];
console.log({ secondHalfSortNum, firstHalfSortNum });
console.log({ secondHalfSort, secondHalfSortNum, sortedArr });
if (secondHalfSortNum > firstHalfSortNum) {
sortedArr.push(firstHalfSortNum);
console.log({ sortedArr });
return;
}
secondHalfSort.shift();
sortedArr.push(secondHalfSortNum);
!secondHalfSort.length && sortedArr.push(firstHalfSortNum);
}
});
return sortedArr;
}
const input = [14, 7, 3, 12, 9, 11, 6, 2];
const expectedOutput = [2, 3, 6, 7, 9, 11, 12, 14];
const actualOutput = mergeSort([...input]);
console.log('Input: ', input);
console.log('Expected Output: ', expectedOutput);
console.log('Actual Output: ', actualOutput);
console.log(`Test case has ${isBothArraySame(expectedOutput, actualOutput) ? 'passed' : 'failed'}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment