Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
Unsure if this implementation of insertion sort is correct?

I found this implementation of insertion sort that avoids using the typical while loop that I've seen across most video explanations. I'm not exactly sure if this is valid though. Wouldn't this be nearly identical to bubble sort? Would there really be any specific benefit of using this? Here are my implementations of insertion sort and bubble sort:

let arr = [1, 4, 6, 7, 8, 6, 3, 4, 5, 6, 6, 7];

const bubbleSort = (array) => {
  for (let i = array.length; i > 0; i--) {
    for (let j = 0; j < i; j++) {
      if (array[j] > array[j + 1])
        [array[j], array[j + 1]] = [array[j + 1], array[j]];
    }
  }
};

const insertSort = (array) => {
  for (let i = 1; i < array.length; i++) {
    for (let j = i; j > 0; j--) {
      if (array[j] < array[j - 1])
        [array[j - 1], array[j]] = [array[j], array[j - 1]];
    }
  }
};


about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your bubble sort implementation is not really bubble sort - rather, it is, as you noticed, essentially the same as your insertion sort implementation.

With bubble sort, you iterate through the list and swap adjacent elements, changing the indicies being compared each time - and when you get to the end, you start over from the beginning of the array and do it again, and so on, until it's sorted. (Nice visualization.) That's not what you're doing.

With insertion sort, you have a completely sorted portion of the array, and an untouched portion of the array, taking elements from the untouched portion and putting them in the right position in the sorted portion before proceeding with the next unsorted item. (Nice visualization.) That's what you're doing in both implementations here.

Would there really be any specific benefit of using this?

No. Both sorting algorithms are far inferior to merge sort (and its variants). If you need to sort an array, the best way by far would be to use the built-in .sort function, which implements merge sort under the hood, and is much faster than any sorting algorithm you could write on your own in JavaScript.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda