4Geeks logo
4Geeks logo

Bootcamps

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Academy

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Full-Stack Software Developer - 16w

Data Science and Machine Learning - 16 wks

Search from all Lessons


LoginGet Started
← Back to Lessons

Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge

Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
Edit on Github

Using javascript to sort a list

Q: I googled and I found a .sort(), so why should I do it manually?
Q: What types of sorting algorithms are there?

Sorting is an expensive task for the computer CPU, it depends on the amount of data and the way the data is organized initially. This mix of possibilities made developers create several algorithmic solutions that can be apllied to every language.

Q: I googled and I found a .sort(), so why should I do it manually?

A: Sorting algorithms is one of the first lessons in Computer Science because it helps you train your mind to think like a computer. It is a great practice to fully understand the concepts of algorithms and code.

Q: What types of sorting algorithms are there?

A: There is more than we can count, the top 10 in popularity are:

Bubble Sorting

It's the simplest of the sorting algorithms. It repeatedly swap adjacent elements to arrange them ascendingly, the algorithm has a "wall" that represents the last position to be compared, the wall keeps moving from right to left, shrinking the comparison size until the entire list is sorted.

Bubble Sort Explained

In Javascript:

1const bubbleSort = (arr) => { 2 let wall = arr.length - 1; //we start the wall at the end of the array 3 while (wall > 0){ 4 let index = 0; 5 while (index < wall) { 6 //compare the adjacent positions, if the right one is bigger, we have to swap 7 if (arr[index] > arr[index + 1]) { 8 let aux = arr[index]; 9 arr[index] = arr[index + 1]; 10 arr[index + 1] = aux; 11 } 12 index++; 13 } 14 wall--; //decrease the wall for optimization 15 } 16 return arr; 17};

📺 In this link, you will find a relly good 2 min video explanation.

📺 Here is a really weird group of bulgarian's dancing the bubble-sort algorithm.

Selection Sorting

Selection also has a wall, but in this case, it marks the beginning of the loop, the algorithm then looks for the smallest item and swaps it with the initial one, then it moves the wall one position to the right to avoid looking again that same item.

Selection Sort Explained

In javascript

1const selectSort = (arr) => { 2 let min = 0; 3 while (min < arr.length-1){ 4 for(let i = min+1; i < arr.length; i++) { 5 if (arr[min] > arr[i]) { 6 let aux = arr[min]; 7 arr[min] = arr[i]; 8 arr[i] = aux; 9 } 10 } 11 min++; 12 } 13 return arr; 14};

📺 In this link, you will find a relly good 3 min video explanation about the selection sort algorithm.

Cocktail Shaker Sorting

Cocktail Shaker works in both fronts at the same time: It looks for the biggest value scanning from left to right and it also looks for the smallest one when its coming back from right to left. It has 2 walls (both for each side of the list), and both walls keep shrinking until they hit each other, when that happens the array is fully sorted.

Selection Sort Explained In javascript:

1const shakerSort = (arr) => { 2 let max = arr.length - 1; 3 let min = 0; 4 while(min < max){ 5 let biggest = min; 6 let smallest = max; 7 // 8 for (var i = min; i <= max; i++) if(arr[biggest] < arr[i]) biggest = i; 9 if(max != biggest){ //swap the items 10 let aux = arr[max]; arr[max] = arr[biggest]; arr[biggest] = aux; 11 } 12 max--; 13 for (var j = max; j >= min; j--) if(arr[smallest] > arr[j]) smallest = j; 14 if(min != smallest){ //swap the items 15 let aux2 = arr[min]; arr[min] = arr[smallest]; arr[smallest] = aux2; 16 } 17 min++; 18 } 19 return arr; 20}

📺 In this link, you will find a relly good 3 min video explanation about the Cocktail Shaker Sort algorithm.

Insertion Sort

Insertion sort involves going through a pile, taking one item, comparing it to the first, swapping places if one item is larger than another and continuing this process until the minimum item is in the correct location.

Insertion sort algorithm In javascript:

1const insertionSort = (arr) => { 2 for (let i = 1; i < arr.length; i++) { 3 let key = arr[i]; 4 let j = i - 1; 5 while (j >= 0 && arr[j].num > key.num) { 6 arr[j + 1] = arr[j]; 7 j--; 8 } 9 arr[j + 1] = key; 10 } 11 return arr; 12};

📺** In this link, you will find a relly good 3 min video explanation about the insertion sort algorithm.

Merge Sort

Merge sort is a more difficult algorithm because it uses recursivity. It is an example of a divide-and-conquer type sorting-algorithm, it splits the unsorted array into two parts and then recursively applies merge sort to these sub-arrays to further split the arrays until you are left with a bunch of single-element arrays. Then, you compare single-element arrays to one another before recombining them into a two-element, sorted array (and so on). It will end up with a single, sorted array of length n.

Merge sort

📺 In this link, you will find a relly good 4 min video explanation about the merge sort algorithm.

Quick Sort

Uses the same "divide and conquer" strategy to gain the same advantages. It first selects a value, which is called the pivot value. The role of the pivot value is to assist with splitting the list. The actual position where the pivot value belongs in the final sorted list, commonly called the split point, will be used to divide the list for subsequent calls to the quick sort.

../_images/firstsplit.png

Partitioning begins by locating two position markers—let’s call them leftmark and rightmark—at the beginning and end of the remaining items in the list (positions 1 and 8 in ). The goal of the partition process is to move items that are on the wrong side with respect to the pivot value while also converging on the split point.

../_images/partitionA.png

We begin by incrementing leftmark until we locate a value that is greater than the pivot value. We then decrement rightmark until we find a value that is less than the pivot value. At this point we have discovered two items that are out of place with respect to the eventual split point. For our example, this occurs at 93 and 20. Now we can exchange these two items and then repeat the process again.

At the point where rightmark becomes less than leftmark, we stop. The position of rightmark is now the split point. The pivot value can be exchanged with the contents of the split point and the pivot value is now in place. In addition, all the items to the left of the split point are less than the pivot value, and all the items to the right of the split point are greater than the pivot value. The list can now be divided at the split point and the quick sort can be invoked recursively on the two halves.

../_images/partitionB.png

The quickSort function invokes a recursive function, quickSortHelper. quickSortHelper begins with the same base case as the merge sort. If the length of the list is less than or equal to one, it is already sorted. If it is greater, then it can be partitioned and recursively sorted. The partition function implements the process described earlier.

Quicksort Algorithm

📺 In this link, you will find a relly good 4 min video explanation about the Quick Sort algorithm.

Aditional Resources

Here is another great visualization with all the most used algorithms: https://codepen.io/msurguy/pen/fBDJA

Here is a real life benchmark of all the mayor sorting algorithms: https://codepen.io/villa7/pen/LyLVbj