Skip to content

Commit

Permalink
feat: Implement bogo sort
Browse files Browse the repository at this point in the history
  • Loading branch information
itsAkshayDubey committed Dec 4, 2024
1 parent 08cba51 commit 0630ed3
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
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);
}
}

0 comments on commit 0630ed3

Please sign in to comment.