Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BogoSort Algorithm Implementation #90

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/Sorts/BogoSort.sol
Original file line number Diff line number Diff line change
@@ -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;
}
}
26 changes: 26 additions & 0 deletions src/Sorts/test/BogoSort.t.sol
Original file line number Diff line number Diff line change
@@ -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);
}
}