Join Leigh Lawhon for an in-depth discussion in this video Merge sort, part of Web Portfolio Projects: Sortable Table and Arrays.
- Next, let's sort and merge the left and right. So, the first thing we're going to do is, we're going to create an empty array called Results, and we'll also create an indexLeft, and that index is going to be set to zero to begin with, and an indexRight, and that's also going to be set to zero. We'll also need that const sorterIndex again, and that's equal to headers.indexOf, and we're going to look at sorters, at the zero index.
Now that we have our variables, we'll loop through our nodes with a While loop, and we're going to say, while indexLeft is less than left.length, and indexRight is less than right.length, then we'll execute the following code. So, here, we're going to need our values again, and we'll borrow our code from our bubbleSort.
Instead of Array I, we're going to be looking at left, indexLeft, and right, and instead of Array J, we're going to be looking at right, indexRight. Now that we have our values, let's compare them. So, if X is less than Y, then we're going to want to results.push, and we'll push left at indexLeft.
Then, we'll iterate our left index with a plus-plus. Else will results.push right at indexRight, and then, iterate our indexRight. Finally, we need to return a concatenated version of all three of our arrays. So, I'll return results.concat, and first, let's concat the left, and we're going to slice that at indexLeft.
Then, we'll concat right.slice at indexRight. Now that we have our nodes, let's go back to where our merge sort is called, and let's pass in itemsNotNull, assign a variable to it, and render our nodes.
Let's check our code in the browser. We'll switch to Merge Sort. We'll drag in Area, and you'll see, Russia once again is at the top.
- 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