Bubble Sortalgorithm
BUBBLE SORT
in this smartcontract you can learn how to use bubble-sort algorithm in solidity.
Problem Description
- Bubble sort algorithm sort data by comparing two consecutive numbers.
- The time complexity of this algorithm is O(n^2).
Problem Solution
- Compare two consecutive number.
- Switch values if the number with higher index value is smaller.
- Finalize the result.
Review
- SmartContract
function _sort(uint[] memory nums) internal pure {
uint n = nums.length; // save gas
for (uint i = 0; i < n; ++i) {
for (uint j = 0; j < n-i-1; ++j) {
// Comparing consecutive data and switching values if value at j > j+1.
if (nums[j] > nums[j + 1]) {
nums[j] = nums[j] + nums[j + 1];
nums[j + 1] = nums[j] - nums[j + 1];
nums[j] = nums[j] - nums[j + 1];
}
}
// Value at n-i-1 will be maximum of all the values below this index.
}
}