Join Leigh Lawhon for an in-depth discussion in this video Insertion sort, part of Web Portfolio Projects: Sortable Table and Arrays.
- [Instructor] To do the insertion sort, let's first pass in the sorter index, and then we'll do a for loop through our nodes. We'll say let I equal one because we're starting with a second element in the array. We'll check that I is less than the array length, and we'll iterate I, so, I plus plus. Inside our for loop, we're going to borrow the code again for row A.
And the x value. Instead of left, we're going to look at arr at the I index. And as we saw in the video, we're going to store that current value. And that's going to be equal to arr, set the I index. Next, we're going to do a backwards for loop, so, the first thing we want to do is define j. So, we'll say let j, and we'll do a backwards for loop, where j is equal to I minus one.
And we'll check to see that j is greater than or equal to zero. And then, we'll negatively iterate j with a minus minus. And inside our for loop, we're going to copy and paste the information from line two 35, and use it to create our row B. And that's going to be the array at the j index. And we'll create our y variable, that will be row B at the sorter index.
Now that we have our values, let's do our check to see, if why is less than or equal to x. And if so, we're going to break. There's no need to swap anything. Else, we'll take array at the index of j plus one, and make it equal array at the index of j. Finally, outside our for loop, we'll have array at j plus one equal our current value.
Finally, outside our first for loop, let's return the array. Upward insertion sort is called. We'll pass in items not null, sorter index, and assign that to a variable, load that will render the nodes. Let's check our code in the browser. We'll select insertion sort, drag area into the sorter well, and once again, Russia is at the top, with the rest of the column properly sorted.
- Sorting your table efficiently
- Filtering null values and sorting nodes
- Sorting algorithms, including merge sort and insertion sort
- Performance testing
- Creating your own algorithm
- Design components
- Adding icons