-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSelectionSort.sol
More file actions
81 lines (71 loc) · 2.33 KB
/
Copy pathSelectionSort.sol
File metadata and controls
81 lines (71 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;
/// @notice Sorting direction
enum SortDirection {
ASC,
DESC
}
/**
* @title Selection Sort
* @notice This contract implements the sort() function for selection sorting of elements in an array
*/
contract SelectionSort {
/**
* @notice Selection Sort
* @param arr Unsorted array of numbers
* @param sortDirection Sorting direction
*/
function sort(uint256[] memory arr, SortDirection sortDirection)
external
pure
returns
(uint256[] memory sortedArr)
{
/// Declare an array to store the sorted elements of the original array
sortedArr = new uint256[](arr.length);
for (uint256 i = 0; i < arr.length; i++) {
/// Sorting in ascending order
if (sortDirection == SortDirection.ASC) {
uint256 index = _findSmallest(arr);
sortedArr[i] = arr[index];
/// Equivalent to removing an element from the array or swapping elements
arr[index] = type(uint256).max;
}
/// Sorting in descending order
if (sortDirection == SortDirection.DESC) {
uint256 index = _findBiggest(arr);
sortedArr[i] = arr[index];
/// Equivalent to removing from the array or swapping elements
arr[index] = type(uint256).min;
}
}
}
/**
* @notice Find the smallest value in the array
* @param arr Unsorted array of numbers
*/
function _findSmallest(uint256[] memory arr) private pure returns (uint256 smallestIndex) {
uint256 smallest = arr[0];
smallestIndex = 0;
for (uint256 i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
smallestIndex = i;
}
}
}
/**
* @notice Find the largest value in the array
* @param arr Unsorted array of numbers
*/
function _findBiggest(uint256[] memory arr) private pure returns (uint256 biggestIndex) {
uint256 biggest = arr[0];
biggestIndex = 0;
for (uint256 i = 1; i < arr.length; i++) {
if (arr[i] > biggest) {
biggest = arr[i];
biggestIndex = i;
}
}
}
}