diff --git a/README.md b/README.md index 487c6b3..8ce079f 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,14 @@ -

+

# 📊 SortingAlgorithms -[![Project Status](https://img.shields.io/badge/status-active-brightgreen.svg)](https://github.com/MartinKondor/SortingAlgorithms/) -[![version](https://img.shields.io/badge/version-21.05-brightgreen.svg)](https://github.com/MartinKondor/SortingAlgorithms/) -[![GitHub Issues](https://img.shields.io/github/issues/MartinKondor/SortingAlgorithms.svg)](https://github.com/MartinKondor/SortingAlgorithms/issues) -![Contributions welcome](https://img.shields.io/badge/contributions-welcome-blue.svg) -[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) - Sorting algorithms visualized. ## Implemented algorithms * Bubble sort + * Insertion sort ### TODO - * Insertion sort * Selection sort * Merge sort * Quicksort diff --git a/index.html b/index.html index 318831d..f4a0a1d 100644 --- a/index.html +++ b/index.html @@ -42,7 +42,7 @@ Forward - @@ -60,8 +60,8 @@ diff --git a/public/js/index.js b/public/js/index.js index 57c0bdc..d24dfb6 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -292,7 +292,39 @@ } function insertionSort(arr) { - console.log("insertionSort"); + for (let i = 1; i < arr.length; i++) { + let currentValue = arr[i]; + let j; + for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { + arr[j + 1] = arr[j]; + } + arr[j + 1] = currentValue; + } + return arr; + } + + function mergeSort(arr) { + if (arr.length <= 1) { + return arr; + } + let mid = Math.floor(arr.length / 2); + let left = mergeSort(arr.slice(0, mid)); + let right = mergeSort(arr.slice(mid)); + return merge(left, right); + } + + function merge(left, right) { + let sortedArr = []; + + while (left.length && right.length) { + if (left[0] < right[0]) { + sortedArr.push(left.shift()); + } else { + sortedArr.push(right.shift()); + } + } + + return [...sortedArr, ...left, ...right]; } // Stores the selected sorting agorithm @@ -358,7 +390,9 @@ if ($('#algorithm').val() === 'insertion') { sortingAlgorithm = insertionSort; } - console.log("ITT VAGYOK"); + if ($('#algorithm').val() === 'merge') { + sortingAlgorithm = mergeSort; + } }); animation.record(function(arr) {