简体   繁体   中英

Insertion sort on an array of objects with javascript

I have this array with objects that look like this

{
 n: 15,
 color: "red"
}

I am trying to sort it with the below function

async insertionSort() {
      let len = this.array.length;
      let value;
      let i;
      let j;
      //let current;
      // let arr = this.array;

      for (i = 0; i < len; i++) {
        value = this.array[i].n;
        //current = this.array[i];
        for (j = i - 1; j > -1 && this.array[j].n > value; j++) {
          //arr[j + 1] = arr[j];
          // HF.arraySwap(this.array, this.array[j + 1], this.array[j]);
          this.array[j + 1] = this.array[j];
        }
        // arr[j + 1] = value;
        HF.arraySwap(this.array, this.array[j + 1], this.array[i]);
        await HF.sleep();
      }
    }

** I cant use array.sort(...) because i am trying to make a visualization of the algorithm, i am using objects in order to change the color of the bars i am rendering on the screen ** When i hit the second for loop i get an error of "Cannot read property 'n' of undefined", when i run it with just numbers it works fine but when i try it with objects it gives the error .I know now i am running out of the array, is there a way i can overcome this and still sort the array of objects? Also, i am using VueJS to display all of this

On the first iteration i=0 , you start second loop with value j=i-1 which is -1. Array doesn't contain item with index -1: array[-1] is undefined . As soon as JavaScript can compare variables of different types it works with numbers because comparison of number and undefined won't trigger an error

By the way you can use Array.proototype.sort method, it will look like:

 console.log(myArr.sort((a,b) => an - bn))
 <script> const myArr = [ { n: 1, color: "red" }, { n: 44, color: "orange" }, { n: 13, color: "yellow" }, { n: 8, color: "green" }, { n: 2, color: "blue" } ]; </script>

Try against this.array[i].n write this.array[i][n] And against this.array[j].n write this.array[j][n]

Is there any reason why not use sort method like this?:

  const arr = [
    { n: 10, color: "red" },
    { n: 20, color: "yellow" },
    { n: 15, color: "black" },
    { n: 7, color: "white" },
    { n: 23, color: "blue" }
  ];

  const ascSorted = arr.sort((a, b) => a.n - b.n); 
  const descSorted = arr.sort((a, b) => b.n - a.n);

  console.log(ascSorted);
  // [
  //   { n: 7, color: "white" },
  //   { n: 10, color: "red" },
  //   { n: 15, color: "black" },
  //   { n: 20, color: "yellow" },
  //   { n: 23, color: "blue" }
  // ];

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