Skip to content

Commit

Permalink
sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
pysel committed Dec 10, 2024
1 parent 877b70d commit 1ffd29f
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ If we decide to use ClvrModel to compute the optimal ordering on chain, we need
Currently, the ordering complexity is O(n^2) where n is the number of swaps.

![Chart!](assets/chart.png)

## Sorting Complexity

![Chart!](assets/sorting.png)
Binary file added assets/sorting.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions src/Sort.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

function quickSort(uint[] memory arr, int left, int right) pure {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}

contract QuickSort {
function sort(uint[] memory data) public pure returns (uint[] memory) {
quickSort(data, int(0), int(data.length - 1));
return data;
}
}
35 changes: 35 additions & 0 deletions test/Sort.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Test} from "forge-std/Test.sol";
import {QuickSort} from "../src/Sort.sol";
import { console } from "forge-std/console.sol";

contract SortTest is Test {
QuickSort public quickSort;

function setUp() public {
quickSort = new QuickSort();
}

function testSort() public {
for (uint256 i = 10; i <= 400; i+=10) {
runSort(i);
}
}

function runSort(uint256 size) public {
uint[] memory data = new uint[](size);
for (uint256 i = 0; i < size; i++) {
data[i] = i % 3;
}

uint256 gas = gasleft();
quickSort.sort(data);
console.log("Gas (in dollars) used for array of size ", size, " gas: ", gas - gasleft());
}

function gasToDollars(uint256 gas) internal pure returns (uint256) {
return gas * 1e9 * 30000 / 1e18;
}
}

0 comments on commit 1ffd29f

Please sign in to comment.