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.