From 0630ed34b1d117550895d346cb5f5913ed26ece2 Mon Sep 17 00:00:00 2001 From: Akshay Dubey Date: Wed, 4 Dec 2024 10:08:57 +0530 Subject: [PATCH] feat: Implement bogo sort --- src/Sorts/BogoSort.sol | 45 +++++++++++++++++++++++++++++++++++ src/Sorts/test/BogoSort.t.sol | 26 ++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 src/Sorts/BogoSort.sol create mode 100644 src/Sorts/test/BogoSort.t.sol diff --git a/src/Sorts/BogoSort.sol b/src/Sorts/BogoSort.sol new file mode 100644 index 0000000..5047098 --- /dev/null +++ b/src/Sorts/BogoSort.sol @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +/** + * @title sort given array using Bogo sort. + * @author [Akshay Dubey](https://github.com/itsAkshayDubey) + * @dev Contract to demonstrate working of bogo sort. + */ + +contract BogoSort { + + // Function to generate a random number between 0 and the given number + function random(uint256 _limit) private view returns (uint256) { + return uint256(keccak256(abi.encodePacked(block.timestamp, block.prevrandao))) % _limit; + } + + // Function to shuffle the array randomly (helper for bogo sort) + function shuffle(uint256[] memory arr) private view { + uint256 n = arr.length; + for (uint256 i = 0; i < n; i++) { + uint256 j = random(n); + // Swap elements at indices i and j + (arr[i], arr[j]) = (arr[j], arr[i]); + } + } + + // Function to check if the array is sorted + function isSorted(uint256[] memory arr) private pure returns (bool) { + uint256 n = arr.length; + for (uint256 i = 1; i < n; i++) { + if (arr[i - 1] > arr[i]) { + return false; + } + } + return true; + } + + // Main Bogo Sort algorithm + function bogoSort(uint256[] memory arr) public view returns (uint256[] memory) { + while (!isSorted(arr)) { + shuffle(arr); + } + return arr; + } +} diff --git a/src/Sorts/test/BogoSort.t.sol b/src/Sorts/test/BogoSort.t.sol new file mode 100644 index 0000000..b974c53 --- /dev/null +++ b/src/Sorts/test/BogoSort.t.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "forge-std/Test.sol"; +import "../BogoSort.sol"; + +contract BogoSortTest is Test { + // Target contract + BogoSort bogoSort; + + /// Test Params + uint256[] public arr = [65, 55, 45, 35, 25, 15, 10]; + uint256[] expected_result = [10, 15, 25, 35, 45, 55, 65]; + + // ===== Set up ===== + function setUp() public { + bogoSort = new BogoSort(); + } + + /// @dev Test `bubbleSort` + + function test_bubbleSort() public { + uint256[] memory result = bogoSort.bogoSort(arr); + assertEq(expected_result, result); + } +}