Insertion Sort is another fundamental sorting algorithm in computer science. It builds the final sorted array one item at a time. It's much like sorting a hand of playing cards - you pick up cards one by one and insert each into its proper position among the cards you've already sorted.
Insertion Sort iterates through the array, growing the sorted portion with each iteration. For each element, it compares it with the already sorted elements, moving them up until it finds the correct position to insert the current element.
Here's a step-by-step breakdown:
Visualization of Insertion Sort:
Recorded gif from https://visualgo.net/en/sorting
Let's take a look at the implementation of Insertion Sort in JavaScript, with detailed comments explaining each part:
function insertionSort(arr) { // Start from the second element (index 1) // We assume the first element is already sorted for (let i = 1; i < arr.length; i++) { // Store the current element we're trying to insert into the sorted portion let currentElement = arr[i]; // Define the starting index of lookup (this is the last index of sorted portion of array) let j = j - 1; // Move elements of arr[0..i-1] that are greater than currentElement // to one position ahead of their current position while (j >= 0 && arr[j] > currentElement) { // Shift element to the right arr[j + 1] = arr[j]; j--; } // We've found the correct position for currentElement (at j + 1), insert it: arr[j + 1] = currentElement; } // The array is now sorted in-place: return arr; }
for (let i = 1; i < arr.length; i++)
Moves forward through the array, selecting one unsorted element (currentElement = arr[i]) at a time.
while (j >= 0 && arr[j] > currentElement)
Looks backward into the sorted portion, shifting larger elements right (arr[j + 1] = arr[j]) to make room for the current element.
arr[j + 1] = currentElement;
Inserts the current element into its correct position, growing the sorted portion.
Insertion Sort builds the final sorted array one item at a time, mimicking how you'd sort a hand of cards. It repeatedly selects a card (element) from the unsorted portion and inserts it into its correct position among the sorted cards, shifting larger cards as needed. This intuitive process makes Insertion Sort efficient for small or nearly-sorted datasets.
Yes, Insertion Sort is a stable sorting algorithm. Stability in sorting algorithms means that the relative order of equal elements is preserved after sorting. Insertion Sort achieves this naturally due to its method of operation:
The stability of Insertion Sort can be particularly useful when sorting complex data structures where maintaining the original order of equal elements is important. For example, when sorting a list of students first by grade and then by name, a stable sort would ensure that students with the same grade remain in alphabetical order by name.
This stability is an inherent property of the basic Insertion Sort algorithm and doesn't require any additional modifications or overhead to achieve, making it a naturally stable sorting method.
Insertion Sort's performance characteristics are as follows:
Time Complexity:
Space Complexity: O(1) - Insertion Sort is an in-place sorting algorithm
Contrairement au tri par sélection, le tri par insertion peut fonctionner correctement sur des tableaux presque triés, atteignant une complexité temporelle proche de la linéaire dans de tels cas.
Avantages :
Inconvénients :
Le tri par insertion, malgré ses limites pour les grands ensembles de données, offre des avantages précieux dans des scénarios spécifiques. Sa nature intuitive, semblable à la façon dont nous pourrions trier les cartes à la main, en fait un excellent outil pédagogique pour comprendre les algorithmes de tri.
Principaux points à retenir :
Bien qu'ils ne soient pas adaptés aux tâches de tri à grande échelle, les principes du tri par insertion sont souvent appliqués dans des méthodes plus sophistiquées. Sa simplicité et son efficacité dans certains scénarios en font un ajout précieux à la boîte à outils algorithmique d'un programmeur.
Le choix de l'algorithme de tri dépend en fin de compte de votre cas d'utilisation spécifique, des caractéristiques des données et des contraintes du système. Comprendre le tri par insertion fournit des informations sur les compromis de conception des algorithmes et jette les bases de l'exploration de techniques de tri plus avancées.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!