Sorting data with TypeScript using the Merge Sort algorithm

After spending some time working on a merge sort implementation in TypeScript, I noticed that half of my array seems to be missing from the final result. Can someone with more experience shed some light on why this might be happening?

Source:

function mergeSort(arr:number[]):number[]{
    if(arr.length <= 1){
        return arr;
    }

    const half:number = Math.floor(arr.length/2);
    const first:number[] = mergeSort(arr.slice(0,half));
    const second:number[] = mergeSort(arr.slice(half + 1));

    return merge(first, second);
}

function merge(a:number[], b:number[]):number[]{
    const c:number[] = [];
    while(a.length && b.length){
        if(a[0]<b[0]){
            c.push(a.shift()!);
        }else{
            c.push(b.shift()!);
        }
    }

    while(a.length){
        c.push(a.shift()!);
    }

    while(b.length){
        c.push(b.shift()!);
    }

    return c;
}

console.log(mergeSort([4, 53, 22, 10, 2, 74, 91, 33, 25, 14, 19, 100, 256, 81, 7, 300]));

Current output: [4, 10, 14, 33, 74, 81, 100, 300] Expected output: [2, 4, 7, 10, 14, 19, 22, 25, 33, 53, 74, 81, 91, 100, 256, 300]

Your insights will be greatly appreciated!

Answer №1

It seems like you are actually missing a number at the half index each time you split your array.

This is because neither of the two slices include the item at the half index.

const first:number[] = mergeSort(arr.slice(0,half));
const second:number[] = mergeSort(arr.slice(half + 1));

To resolve this issue, you need to ensure that the item at the half index is included, either in the first half:

const first:number[] = mergeSort(arr.slice(0,half + 1));

Or include it in the second half:

const second:number[] = mergeSort(arr.slice(half));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

What is the reason Nav cannot be directly used in the constructor instead of using @ViewChild(Nav) nav: Nav in Ionic?

As a newcomer to Ionic, I am trying to understand the code snippet provided. My confusion lies in the purpose of "NAV" and why it is used in @viewchild(). While I can access the MenuController by using it in the constructor, I am unable to use NAV in the s ...

Angular controller classes were unable to recognize the TypeScript class within the class constructor

Encountering a problem while attempting to create a property for the model class within my angular controller using the constructor. Take a look at my code below: app.ts module app { angular .module("formApp", [ "n ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Add fresh data key and corresponding value into an array containing multiple objects

Inserting an accountId key and value into the this.membersForm.value object is the goal, while also setting the id to 0 and adding memberId: id to the this.membersForm.value.teamMembersDto object. How can we achieve this task of inserting the accountId ke ...

Identify the category of the component

Using a Link component from version 4.0.0-beta.2, I am exploring its capability to override the root element with a field called component. My goal is to wrap the Link component in a new component called MyLink and pass a custom component through props: ...

Converting a JavaScript project into a TypeScript one

My current project, a web interface, is structured as follows: Directory: L:\root-of-project Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 16/01/2019 11:25 ...

C++ Recursive Implementation of Fibonacci's Algorithm

I've encountered an issue with my code related to a Fibonacci function. I have two files named In0201.txt and Out0201.txt. The program is supposed to read the value from the "In0201.txt" file and write the results to Out0201.txt. Instead of writing a ...

What is the best way to arrange a collection of JObjects in VB.net?

Currently, I am working with VB.net (4.5) and utilizing the Newtonsoft Json Linq package. Within my code, there is an array named BuyList that consists of 100 market orders structured as follows: {{ "Quantity": 0.14333804, "Rate": 6693.01 }} My obje ...

Is there a way to access a specific tab index in Ionic 3.20 from a child page using a function call?

Imagine having a tabs page with 3 index pages. The first index page is the home page, the second is the products page, and the third is the cart page. When navigating from the home page to the search page, there is a button that you want to click in orde ...

What is the correct way to add type annotations to an Axios request?

I have meticulously added type annotations to all endpoints in my API using the openapi-typescript package. Now, I am looking to apply these annotations to my Axios requests as well. Here is a snippet of code from a Vue.js project I have been developing: ...

What could be causing the ng-if function to continuously loop?

I have encountered an issue where I am passing a boolean function in the ngIf attribute instead of a boolean condition in my HTML template file. This boolean function seems to be repeating itself depending on the amount of data present in the variable &apo ...

Showing Nested Numerical Objects Post RequestBeing Made

Currently, I am facing an issue with accessing nested objects referred to by numbers. After making a service call to retrieve a JSON object, I mapped each field to another object which will be used for displaying the fields in HTML. The problem arises whe ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

A recursive function that creates the error message "Using type 'never' as an index type is not allowed."

I found myself wanting to create a recursive private function within a class that would iterate through the nested properties of an object, no matter how many levels deep they go. private loop(item:any) { for(let property in item){ if (typeof ...

What is the best way to retrieve a variable that has been exported from a page and access it in _

Suppose this is my pages/visitor.tsx const PageQuery = 'my query'; const Visitor = () => { return <div>Hello, World!</div>; }; export default Visitor; How can I retrieve PageQuery in _app.tsx? One approach seems to be by assi ...

How can we declare React context functions to avoid any potential linting problems?

Working with React Context, I currently have: const DocumentContext = createContext< [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>] >([initVal, () => { }, () => { }]); However, I am receiving a complaint from my ...

How come the type declaration ( () => string ) suddenly pops up?

I am currently utilizing the jasonwebtoken package and have encountered a new javascript/typescript behavior. interface JwtPayload { [key: string]: any; iss?: string | undefined; sub?: string | undefined; aud?: string | string[] | undefined ...

dynamic padding style based on number of elements in array

Is there a way to set a padding-top of 10px only if the length of model.leaseTransactionDto.wagLeaseLandlordDto is greater than 1? Can someone provide the correct syntax for conditionally setting padding based on the length? Thank you. #sample code <d ...