diff --git a/Sorting/BubbleSort.sol b/Sorting/BubbleSort.sol new file mode 100644 index 0000000..2256ad3 --- /dev/null +++ b/Sorting/BubbleSort.sol @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +/** + * @title BubbleSort + * @dev Implementation of Bubble Sort algorithm in Solidity. + * This function sorts an array of unsigned integers in ascending order. + */ +contract BubbleSort { + function bubbleSort(uint[] memory arr) public pure returns (uint[] memory) { + uint n = arr.length; + for (uint i = 0; i < n - 1; i++) { + for (uint j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + uint temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + return arr; + } +} diff --git a/Sorting/testSort.sol b/Sorting/testSort.sol new file mode 100644 index 0000000..1c7897b --- /dev/null +++ b/Sorting/testSort.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "remix_tests.sol"; +import "../Sorting/BubbleSort.sol"; + +contract TestBubbleSort { + BubbleSort sorter; + + function beforeAll() public { + sorter = new BubbleSort(); + } + + function testSorting() public { + uint ; + arr[0] = 9; + arr[1] = 3; + arr[2] = 7; + arr[3] = 1; + arr[4] = 5; + + uint[] memory result = sorter.bubbleSort(arr); + Assert.equal(result[0], uint(1), "First element should be 1"); + Assert.equal(result[4], uint(9), "Last element should be 9"); + } +}