From c1f3de11b176bb4490b7f3dc52ce9fe9d39503da Mon Sep 17 00:00:00 2001 From: Jakob Jung Date: Sat, 9 Oct 2021 17:13:29 +0200 Subject: [PATCH] I couldn't help myself and needed to add my all time favorite bogo_sort.m --- README.md | 1 + algorithms/sorting/bogo_sort.m | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 algorithms/sorting/bogo_sort.m diff --git a/README.md b/README.md index fe6a63b..aa77183 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ You can run and edit the algorithms or contribute to them using [Gitpod.io](http * other * [tic_tac_toe](https://github.com/TheAlgorithms/MATLAB-Octave/blob/master/algorithms/other/tic_tac_toe.m) * sorting + * [Bogo Sort](https://github.com/TheAlgorithms/MATLAB-Octave/blob/master/algorithms/sorting/bogo_sort.m) * [Bubble Sort](https://github.com/TheAlgorithms/MATLAB-Octave/blob/master/algorithms/sorting/bubble_sort.m) * [Counting Sort](https://github.com/TheAlgorithms/MATLAB-Octave/blob/master/algorithms/sorting/counting_sort.m) * [Insertion Sort](https://github.com/TheAlgorithms/MATLAB-Octave/blob/master/algorithms/sorting/insertion_sort.m) diff --git a/algorithms/sorting/bogo_sort.m b/algorithms/sorting/bogo_sort.m new file mode 100644 index 0000000..8f19e49 --- /dev/null +++ b/algorithms/sorting/bogo_sort.m @@ -0,0 +1,25 @@ +% This is a pure Matlab implementation of the bogosort algorithm, +% also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. +% Bogosort generates random permutations until it guesses the correct one. +% More info on: https://en.wikipedia.org/wiki/Bogosort +% +% Example-Run: bogo_sort([2,5,-10,22,48,2]) + + +function collection = bogo_sort(collection) + while is_sorted(collection) == 0 + collection = collection(randperm(length(collection))); + end +end +function is_sorted_bool = is_sorted(collection) + is_sorted_bool = 1; + if length(collection) < 2 + return + end + for i = 1: (length(collection)-1) + if collection(i) > collection(i + 1) + is_sorted_bool = 0; + return + end + end +end \ No newline at end of file