简体   繁体   中英

JavaScript Bubble & Insertion sort for objects in an array

I'm trying to bubble sort by price and insert sort by name but I'm confused about how to print the sorted list. Do I just console.log because I tried that and it just printed the array but without it being sorted? Am I supposed to return something? (pls don't mind the formatting I'm new here sorry!)

    //Class 

      class Shoe{
          constructor(name, price, type) {
          this.name = name;
          this.price = price;
          this.type = type;
          }
     }

    // list of objects
    var shoes = [
        new Shoe('Nike AirMax 90', '120', 'Casual'),
        new Shoe('Jordan Retro 1', '110', 'Casual'),
        new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),
        new Shoe('Adidas X Ghosted', '110', 'Athletic'),
        new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),
        new Shoe('Aldo Loafers', '130', 'Formal'),
        new Shoe('Timberlands', '199', 'Seasonal boots'),
        new Shoe('Converse High Tops', '70', 'Casual'),
        new Shoe('Converse Low Tops', '80', 'Casual'),
        new Shoe('Adidas NMDs', '110', 'Athletic'),
        new Shoe('Heels', '130', 'Formal'),
        new Shoe('Nike AirForce', '150', 'Casual')
    ];

    // bubble sort
       function bubbleSort(shoes) {
         var swapped;
         do {
           swapped = false;
              for (var i=0; i < shoes.length-1; i++) {
                 if (shoes[i].price > shoes[i+1].price) {
                    var temp = shoes[i];
                    shoes[i] = shoes[i+1];
                    shoes[i+1] = temp;
                    swapped = true;
                 }
              }
          } while (swapped);
        }

       // insertion sort
       function insertionSort(shoes) {
          let a = shoes.length;
              for (let i = 1; i < a; i++) {
              // Choosing the first element in our unsorted subarray
                  let first = shoes[i];
        // The last element of our sorted subarray
                  let l = i-1; 
                  while ((l > -1) && (first.type < shoes[l].type)) {
                       shoes[l+1] = shoes[l];
                       l--;
                  }
                  shoes[l+1] = first;
               }
           return shoes;
        }

Any help is really appreciated, thank you!

Sort functions can either sort the input data by mutating/ altering the input, or by taking and returning a sorted copy, which leaves the original untouched. Either type is an acceptable way to do things.

In your example, both of your sorts mutate the passed in data, so while they can return the array as a convenience (like your insertion sort already does), bear in mind that the original array is still changed regardless of whether the returned value is recorded.

A problem you're running into here that I can see, however, is actually about string conversion- you need to convert your prices to numbers to compare them properly. At the moment, you're performing string comparison.

There's more than a few ways to do this , but I personally like the unary plus .

 class Shoe { constructor(name, price, type) { this.name = name; this.price = price; this.type = type; } } var shoes = [ new Shoe('Nike AirMax 90', '120', 'Casual'), new Shoe('Jordan Retro 1', '110', 'Casual'), new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'), new Shoe('Adidas X Ghosted', '110', 'Athletic'), new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'), new Shoe('Aldo Loafers', '130', 'Formal'), new Shoe('Timberlands', '199', 'Seasonal boots'), new Shoe('Converse High Tops', '70', 'Casual'), new Shoe('Converse Low Tops', '80', 'Casual'), new Shoe('Adidas NMDs', '110', 'Athletic'), new Shoe('Heels', '130', 'Formal'), new Shoe('Nike AirForce', '150', 'Casual') ]; function bubbleSort(shoes) { var swapped; do { swapped = false; for (var i = 0; i < shoes.length - 1; i++) { // Must convert prices to numbers, // otherwise they get compared as strings if (+shoes[i].price > +shoes[i + 1].price) { var temp = shoes[i]; shoes[i] = shoes[i + 1]; shoes[i + 1] = temp; swapped = true; } } } while (swapped); return shoes; } bubbleSort(shoes); console.log('Bubble Sort:\\n', shoes);

Not sure of the reason you are writing sorts from scratch. Don't get me wrong, I like to 'roll my own' on a lot of stuff, but if you want to do a sort you can just do:

shoes.sort(function (a, b) {return a.price - b.price});

As for your displaying your results, I usually just make a simple html page with a div element and a button. When I click the button I have my function fill in the div using the div's innerText property with the result. Just remember when sending objects or arrays to an display, you will probably want to use JSON.stringify so you get the actual contents instead of just

[object Object],[object Object],[object Object]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM