Basic Sorting Algorithms
This week in my Algorithms and Data Structures Masterclass I learned about a few basic sorting algorithms. While they are not the most efficient algorithms to sort data, they can be very useful when sorting smaller specific datasets. I will be focusing on Bubble, Selection, and Insertion Sort. Let’s discuss how each works and go over an example of each.
Bubble Sort:
function bubbleSort(arr){
// let noswaps = true;
for(let i=arr.length;i>0;i--){
for(let j=0;j < i-1;j++){
console.log(arr[j],arr[j+1])
if(arr[j] > arr[j+1]){
let temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
// noswaps = false
}
}
// if(noswaps){
// break;
// }
}
return arr
}bubbleSort([25,49,21,13,67,81]);
This Bubble Sort solution works by using a nested for loop to compare the value at arr[j] and arr[j + 1]. Bubble sorting typically works by iterating through the array once, comparing two values next to each other, and swapping the values if one is less than the other. Bubble Sorting works very well if the data set is already mostly sorted, because very few swaps are required.
Selection Sort:
function selectionSort(arr){
// let noswaps = true;
for(let i=0;i<arr.length;i++){
let min = i;
for(let j=i+1;j<arr.length;j++){
console.log(arr[i],arr[j])
if(arr[j] < arr[min]){
min = j
}
}
let temp = arr[i]
arr[i] = arr[min]
arr[min] = temp
}
return arr
}selectionSort([25,49,21,13,67,81]);
This Selection Sort solution works by creating a variable named min, then using a nested for loop to compare the current value at arr[j] to the min or lowest value. Selection sorting typically works by iterating through the array multiple times, comparing the min value to the current value. A swap is made when the current value is less than the lowest value or min. Selection Sorting is generally not recommend for mostly sorted datasets because it will iterate through the array multiples times regardless if the data is sorted or not.
Insertion Sort:
function insertionSort(arr){
var currentVal;
for(var i = 1; i < arr.length; i++){
currentVal = arr[i];
for(var j = i - 1; j >= 0 && arr[j] > currentVal; j--) {
arr[j+1] = arr[j]
}
arr[j+1] = currentVal;
}
return arr;
}insertionSort([25,49,21,13,67,81]);
This Insertion Sort solution works by creating a sorted portion of the array and compares our current value to every value in the sorted portion of our array. The current value is placed within our sorted portion once the inner for loop requirements are no longer met. Insertion sorting typically works by iterating through the array once, comparing the first value in our sorted portion to the current value. A swap is made if that first value is greater than the current value. Similar to Bubble sorting, Insertion Sort also works very well with mostly sorted datasets.