0

I have an array filled with objects "fruits" which have properties "kind", "color". I need to use

quicksort 

method to sort given fruits by their colors in accordance to a given order of colors. For example, an array "fruits" has

 {kind: apple, color: red}; {kind: orange, color: orange}; {kind: watermelon, color: green}; {kind: blueberry, color: blue}.

And you need to sort these fruits in accordance to rainbow color orders. How do we do that? All examples, that I have found on the internet only deal with numbers. I know that first step is to make a function which tells us the weight of a color in a given order:

const comparationColor = (fruit1, fruit2) => {
  const priority = ['violet', 'indigo', 'blue', 'green', 'yellow', 'orange', 'red'];
  const priority1 = priority.indexOf(fruit1.color);
  const priority2 = priority.indexOf(fruit2.color);
  return priority1 > priority2;
};  

And then there is a

quickSort 

function:

quickSort (arr) {
    if (arr.length < 2) {
        return arr;
    }
    
      let pivot = arr[0];
      let leftArr = [];
      let rightArr = [];
    
    for (let i = 1; i < arr.length; i++) {
          if (comparation(pivot, arr[i])) {
          leftArr.push(arr[i]);
        } else {
          rightArr.push(arr[i]);
        }
      }
      return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
      }

But how do I combine them?

3
  • What's the expected output? See this? if (comparationColor(pivot, arr[i]) > 0)? Commented May 30, 2024 at 20:59
  • Why would you do that with quick sort? When you have a limited set of keys, like 7 colors, then you're much better off by creating 7 buckets in the order of the rainbow colors, and then you can store all objects in their proper bucket. At the end concatenate those buckets. Done. Commented May 30, 2024 at 21:47
  • Because it's an assignment. And it's not particularly 7 colors, that's for an example, there could be 15 colors or any other property and you set any order of this property, and quicksort should sort an array according to that order. Commented May 30, 2024 at 21:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.