2-min Bubble Sort(of pointless?) — Algorithm Basics —
Bubble Sort, its a horrible sorting method, especially if not optimized; But its great as an introduction into sorting.
First and foremost, what is Bubble Sort?
Bubble Sort is a sorting algorithm which takes a list, compares items in the list and if one item in the list is greater than the other, they are swapped; this process is repeated until all greater values are Bubbled up to the top, and the lesser values sink to the bottom(Sometimes, probably just to be different, people refer to the Bubble Sort as the Sinking Sort..)
Understanding that a Bubble Sort it swapping values, the first thing we will do is create a swapping function. this function will take in an array, and two indexes;
function swap(arr, index1, index2){}
inside of the function we will swap the values of index one with index2 and index2 with index1;
//ES2015
function swap(arr, index1, index2){
[arr[index1], arr[index2]] = [arr[index2],arr[index1]
}
Ok, so we have our swapping function, when called it will set the values of arr[index1] and arr[index2] to each others values, effectively swapping their values. Make sense?
Next… We Build out our BubbleSort function, this just needs one parameter, an Array…
Bubble Sort Time.
Just keep in mind, the bubble sort is not an efficient sorting algorithm, it has a Quadratic Time Complexity O(N²)(which is horrible, from 1 being good and 6 being horrible, we are at a 5; look into Big-O time complexity if interested.).
So back to the function.
We are going to be efficient, I’m not going post the Naive approach; i’m not trying to have that garbage in my sensitive brain.
Bubble Sort Algorithm Starts Here
We start by creating a function, we are going to name it bubbleSort, this function is going to take in an Array, and immediately we are going to go into a nested For-Loop.. yeah gross.
function bubbleSort(arr){
//we are going to set out i value to the array.length so that we are
//not going over the full length of the array every iteration.
for(let i = arr.length; i>0;i--){
for(let j = 0; j<i; j++){
//if the current index is greater than the next index, we Swap //<strong/>
if(arr[j]> arr[j+1]){
swap(arr, j, j+1);
}
}
}
}
If you have a better way of accomplishing this, please post below, any questions feel free to comment or connect with me on LinkedIn @ LinkedIn.com/adanieljohnson
Also, M-F @7:30 PST I run an Algorithm walk through zoom meeting. Connect with me on LinkedIn for an Invite.
There is no end to education. It is not that you read a book, pass an examination, and finish with education. The whole of life, from the moment you are born to the moment you die, is a process of learning.
— Jiddu Krishnamurti