How about creating a customized sorting algorithm from the ground up that incorporates a comparator?

My current assignment requires me to create a unique sorting method from scratch (cannot use Array.sort()) that accepts a comparator and organizes a list based on that comparator.

const people = [
  {name: 'Bill', age: 30, likes: 'food'},
  {name: 'Andrew', age: 17, likes: 'games'},
  {name: 'Kyle', age: 59, likes: 'cats'},
]

function sortArr(comparator, array) {
  // your code here
}

function exampleComparator(int1, int2) {
  if (int1 > int2) {
    return true;
  } else {
    return false;
  }
}

One of the comparators I need to create will sort the list by name, while another will sort it by age.

To use the function, I would input: sortArr(ageComparator, people), which should then sort the array based on the age of the people.

However, I'm encountering significant difficulties with the sorting array. Initially, I considered using the native array sort method, but my professor has explicitly prohibited that. I'm unsure of how to approach the sortArr function to incorporate a comparator that returns a boolean value for sorting.

While I can implement a basic insertion sort, I'm struggling with integrating the comparator into the process.

If anyone could guide me in the right direction, I would greatly appreciate it. Are there alternative sorting algorithms that could make this task more manageable?

Thank you.

Answer №1

Upon closer inspection of the provided example comparator

function exampleComparator(int1, int2) {
  if (int1 > int2) {
    return true;
  } else {
    return false;
  }
}

It is evident that the primary objective is to implement a sorting algorithm where a comparator is utilized to assess int1 and int2 (or object1 vs object2 in a broader context). For instance, consider the bubble sort algorithm below:

function sortArr(inputArr) {
  let len = inputArr.length;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - i - 1; j++) {
      if (inputArr[j] > inputArr[j + 1]) { // the comparison occurs here
        let tmp = inputArr[j];
        inputArr[j] = inputArr[j + 1];
        inputArr[j + 1] = tmp;
      }
    }
  }
}

Therefore, it becomes necessary to include a custom comparator in order to facilitate the comparison process, such as sorting by age in ascending order:

const people = [{
    name: 'Bill',
    age: 30,
    likes: 'food'
  },
  {
    name: 'Andrew',
    age: 17,
    likes: 'games'
  },
  {
    name: 'Kyle',
    age: 59,
    likes: 'cats'
  },
]

function ageComparator(a, b) {
  if (a.age > b.age) {
    return true;
  } else {
    return false;
  }
}

function sortArr(comparator, inputArr) {
  let len = inputArr.length;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - i - 1; j++) {
      if (comparator(inputArr[j], inputArr[j + 1])) {
        let tmp = inputArr[j];
        inputArr[j] = inputArr[j + 1];
        inputArr[j + 1] = tmp;
      }
    }
  }
}

sortArr(ageComparator, people)
console.log(people)

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

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

What is causing my Directive to trigger the error "Error: $injector:unpr Unknown Provider"?

I have been diligently working on updating my Controllers, Factories, and Directives to align with the recommended Angular Style Guide for Angular Snippets. So far, I have successfully refactored the Controllers and Factories to comply with the new style ...

Merging two JSON objects in the absence of one

function fetchData(url) { return fetch(url).then(function(response) { return response.json(); }).then(function(jsonData) { return jsonData; }); } try { fetchData(`https://api.hypixel.net/skyblock/auctions?key=${apikey}`).the ...

Best practices for building an Ember frontend and Node backend application

I'm currently working on a project that involves an ember frontend and a node backend. Within my ember-cli app, I've configured the .ember-cli file to proxy requests to node like this: { "proxy": "http://localhost:3000" } I've had to es ...

JS/Electron Insert items individually

Apologies if my explanation is unclear. I have a function (shown below) that parses a JSON file and creates a grid of 1550 items. How can I add them one by one instead of all at once? Loading all 1500 items together is taking too long. function addItem () ...

Utilizing TypeScript to Populate an observableArray in KnockoutJS

Is there a way to populate an observableArray in KnockoutJS using TypeScript? My ViewModel is defined as a class. In the absence of TypeScript, I would typically load the data using $.getJSON(); and then map it accordingly. function ViewModel() { var ...

JavaScript's prototypical inheritance model allows objects to inherit properties and

Exploring javascript's prototypical inheritance and object-oriented programming is new to me. I attempted to create a base object called Account and then inherit the CheckingAccount from it. Below is my code snippet. function Account(fName, lName) { ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...

Open a fresh window using Javascript and add new content inside

After creating a script that opens a window and writes content when the button is clicked once, I noticed that clicking the button again causes the window to gain focus instead of rewriting the content. Does anyone have any ideas on how to fix this issue ...

Next.js pages do not respond to event listeners

Something strange is happening in my Next.js project. I've implemented a header that changes color as the page scrolls using the useEffect hook: The hook in the Header component looks like this: React.useEffect(() => { window.addEventListener(&a ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

Error encountered: SyntaxError - Missing semicolon before statement in AJAX call while processing JSON data

I am currently in the process of making a cross domain JSONP call utilizing this code snippet: jQuery.ajax({ async: true, url: 'http://mnews.hostoi.com/test.json', dataType: 'jsonp', method: "GET&quo ...

$.ajax causing a JSON input string malfunction

My web API requires the following JSON format for input: [{ "atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe", "atrSpaClassLegendId": "00D18EECC47E7DF44200011302", "atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"}, { "atrSpaUserId": "47 ...

When using NextJS with next-i18next and Firebase functions, all pages are redirected to a 404 error page if the locale is included

I have implemented next-i18next with Next.js in a setup that involves SSR deployed to Firebase functions. I followed the guidelines provided in this documentation https://github.com/i18next/next-i18next During development, everything functions correctly, ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve ...

Why does AngularJS $watch only execute once?

Why do the codes in the watch only run once? How can I address this issue? this.$rootScope.$watch('tabType', () => { if (this.$rootScope["tabType"] === TabType.Sent) { this.$scope.refreshSentList(); } else if (this.$rootScope[ ...

Error encountered when converting Linestring data to an array in OpenLayers due to missing value

As a newcomer to OpenLayers, I am facing a basic problem and would appreciate your help. I'm looking to draw a line using a different method instead of relying on OpenLayers.Control. Below is a snippet of my code: (where coordinates are taken as a f ...

What could be causing my React child component to not update when changes are made to an array passed down in props after fetching new data?

My Profile.js component is responsible for fetching activity data related to a specific user from the URL parameter and updating the profileActivity state. This state is then passed down to my child component, ProfileActivity.js, where it should be display ...