From f6bfe07f065cb5a2a7fb0947f83070396b371946 Mon Sep 17 00:00:00 2001 From: Pedro Date: Fri, 15 Dec 2023 09:59:44 -0400 Subject: [PATCH] add bogosort in javascript --- bogosort/bogosort.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 bogosort/bogosort.js diff --git a/bogosort/bogosort.js b/bogosort/bogosort.js new file mode 100644 index 00000000..8028f02e --- /dev/null +++ b/bogosort/bogosort.js @@ -0,0 +1,31 @@ +/** + * Implements the Bogo Sort algorithm to sort an array in ascending order. + * Bogo Sort is an inefficient sorting algorithm that randomly shuffles the array until it is sorted. + * This algorithm has an average-case time complexity of O((n+1)!), making it highly impractical for large arrays. + * + * @param {number[]} array - The array to be sorted. + */ +function bogosort(array) { + let flag = false; + let count = 0; + + while (!flag) { + count++; + for (let i = 0; i < array.length; i++) { + if (i == array.length - 1) { + flag = true; + console.log("success: ", count); + console.table(array); + break; + } + if (array[i] > array[i + 1]) { + array.sort((a, b) => 0.5 - Math.random()); + console.log("failure: ", count); + break; + } + } + } +} + +let array = [1, 3, 5, 2, 4, 8, 9, 7, 6]; +bogosort(array);