├── insertionSort.js ├── quickSort.js ├── bubbleSort.js └── mergeSort.js /insertionSort.js: -------------------------------------------------------------------------------- 1 | insertionSort = (array) => { 2 | for (outer = 1; outer < array.length; outer++) { 3 | for (inner = 0; inner < outer; inner++) { 4 | console.log(array.join(' ')) 5 | if (array[outer] < array[inner]) { 6 | const [element] = array.splice(outer, 1) 7 | array.splice(inner, 0, element) 8 | } 9 | } 10 | } 11 | console.log(array.join(' ')) 12 | return array 13 | } 14 | const numbers = [8, 5, 6, 9, 3, 1, 4, 2, 7, 10] 15 | insertionSort(numbers) -------------------------------------------------------------------------------- /quickSort.js: -------------------------------------------------------------------------------- 1 | quickSort = (array) => { 2 | if (array.length < 2) { 3 | return array 4 | } 5 | const chosenIndex = array.length - 1 6 | const chosen = array[chosenIndex] 7 | const a = [] 8 | const b = [] 9 | for (let i = 0; i < chosenIndex; i++) { 10 | const temp = array[i] 11 | temp < chosen ? a.push(temp) : b.push(temp) 12 | } 13 | 14 | const output = [...quickSort(a), chosen, ...quickSort(b)] 15 | console.log(output.join(' ')) 16 | return output 17 | } 18 | const numbers = [8, 5, 6, 9, 3, 1, 4, 2, 7, 10] 19 | quickSort(numbers) -------------------------------------------------------------------------------- /bubbleSort.js: -------------------------------------------------------------------------------- 1 | bubbleSort = (array) => { 2 | let swapped = false 3 | do { 4 | swapped = false 5 | array.forEach((current, i) => { 6 | console.log(array.join(' ')) 7 | if (current > array[i + 1]) { 8 | const temp = current 9 | console.log(array.join(' ')) 10 | 11 | array[i] = array[i + 1] 12 | array[i + 1] = temp 13 | swapped = true 14 | } 15 | }) 16 | } while(swapped) 17 | console.log(array.join(' ')) 18 | return array 19 | } 20 | 21 | const numbers = [8, 5, 6, 9, 3, 1, 4, 2, 7, 10] 22 | bubbleSort(numbers) -------------------------------------------------------------------------------- /mergeSort.js: -------------------------------------------------------------------------------- 1 | divide = (array) => { 2 | if (array.length < 2) { 3 | return array 4 | } 5 | const mid = Math.floor(array.length/2) 6 | const smallOne = array.slice(0, mid) 7 | const smallTwo = array.slice(mid) 8 | return sort(divide(smallOne), divide(smallTwo)) 9 | } 10 | 11 | sort = (smallOne, smallTwo) => { 12 | const sorted = [] 13 | while(smallOne.length && smallTwo.length) { 14 | if (smallOne[0] <= smallTwo[0]) { 15 | sorted.push(smallOne.shift()) 16 | } else { 17 | sorted.push(smallTwo.shift()) 18 | } 19 | } 20 | const output = [...sorted, ...smallOne, ...smallTwo] 21 | console.log(output) 22 | return output 23 | } 24 | 25 | const numbers = [8, 5, 6, 9, 3, 1, 4, 2, 7, 10] 26 | console.log(divide(numbers)) --------------------------------------------------------------------------------