Sorting Demo

MergeSort Bubble Sort QuickSort RadixSort Insertion Sort

by dpnminh

HTML

<div>
 <label for="size">Array size</label>
 <input name="size" id="size" min=1 type="number">
</div>
<div>
<br/>
<button onclick="sortAlgorithm('MergeSortInplace')">
In-place Recursive Merge Sort
</button>
<button onclick="sortAlgorithm('RecursiveMergeSort')">
Recursive Merge Sort
</button>
<button onclick="sortAlgorithm('NonRecursiveMergeSort')">
Non-Recursive Merge Sort
</button>
<button onclick="sortAlgorithm('BubbleSort')">
Bubble Sort
</button>
<button onclick="sortAlgorithm('InsertionSort')">
Insertion Sort
</button>
</div>
<br/>
<div class="original">
  <span id="original"></span>
</div>
<div class="result">
  <span id="result"></span>
</div>

JavaScript

function sortAlgorithm(type){
	var size = parseInt(document.getElementById('size').value) || 1;
	var arr = Array.from({length: size}, () => Math.floor(Math.random() * 40));
  var selectedAlgorithm = "";
  document.getElementById('original').innerHTML = arr.toString();
  
  var algorithms = {
  	MergeSortInplace: {
    	name: "In-place Recursive Merge Sort",
      play: MergeSortInplace
    },
    RecursiveMergeSort: {
    	name: "Recursive Merge Sort",
      play: RecursiveMergeSort
    },
    NonRecursiveMergeSort: {
    	name: "Non-rescursive Merge Sort",
      play: NonRecursiveMergeSort
    },
    BubbleSort: {
    	name: "Bubble Sort",
      play: BubbleSort
    },
    InsertionSort: {
    	name: "Insertion Sort",
      play: InsertionSort
    },
    QuickSort: {
    	name: "QuickSort",
      play: QuickSort
    },
    RadixSort: {
    	name: "RadixSort",
      play: RadixSort
    }
  };
  
  if (algorithms[type]){
  	selectedAlgorithm = algorithms[type].name + " : ";
    
    if (type === 'RecursiveMergeSort'){
    	arr = algorithms[type].play(arr);
    }
    else {
    	algorithms[type].play(arr, 0, arr.length - 1);
    }
  }
  
  document.getElementById('result').innerHTML = selectedAlgorithm + ": " + arr.toString();
}

//MergeSort

function MergeSortInplace(A, start, end){
  if (start >= end) return;
  var middle = Math.floor((start + end) / 2);
  MergeSortInplace(A, start, middle);
  MergeSortInplace(A, middle + 1, end);
  Merge(A, start, middle, end);
}

function Merge(A, start, middle, end){
  var leftArr = [], rightArr = [], leftIndex = 0, rightIndex = 0, i = start;
  
  leftArr = A.slice(start, middle + 1);
  rightArr = A.slice(middle + 1, end + 1);
  
  while (leftIndex <leftArr.length && rightIndex < rightArr.length && i < end + 1){
  	if (leftArr[leftIndex] < rightArr[rightIndex]){
    	A[i] = leftArr[leftIndex];
      leftIndex++;
    }
    else{
    	A[i] = rightArr[rightIndex];
      rightIndex++;
    }
    
    i++;
  }
  
  while (leftIndex...