JSFiddle - React, Tailwind, and code Playground
by nkdweb
HTML
<div id="newArr">Original array: </div>
<div id="sortArr">Sorted array: </div>
<div id="sortFlow">
</div>
JavaScript
// Unsorted array
var array = [1, 8, 3, 2, 5];
document.getElementById('newArr').innerHTML += array;
// Make a copy of the original array
var sortedArray = array;
// Sort array (ascending)
function arraysort() {
// This swapped 'flag' tells the function whether or not it will
// need to iterate over the array again to continue sorting
var swapped = false;
for( var i = 1; i < array.length; i++ ) {
var prev = array[i - 1];
var current = array[i];
// If the previous number is > than the current, swap them around
if( prev > current ) {
swapped = true;
sortedArray[i] = prev;
sortedArray[i - 1] = current;
document.getElementById('sortFlow').innerHTML += sortedArray;
}
}
// If there has been a swap, sort over the array again
if( swapped ) {
return arraysort();
}
document.getElementById('sortArr').innerHTML += sortedArray;
}
// Run the sort function
arraysort();