# 控制流和插入排序 **Published by:** [startha](https://paragraph.com/@starha/) **Published on:** 2023-09-22 **URL:** https://paragraph.com/@starha/V0AHROpwTzoNj68q5dJ2 ## Content 控制流 solidity的控制流与其他语言类似,主要包括一下集中: if-else //if-else function ifElseTest(uint256 _number) public pure returns(bool) { if(_number == 0) { return true; } else { return false; } } for //for function forLoopTest() public pure returns(uint256) { uint sum = 0; for(uint i = 0; i < 10; i++) { sum += i; } return sum; } while //while function whileTest() public pure returns(uint256) { uint sum = 0; uint i = 0; while(i < 10) { sum += i; i++; } return sum; } do-while //do-while function doWhileTest() public pure returns(uint256) { uint sum = 0; uint i = 0; do { sum += i; i++; }while(i < 10); return sum; } 三元运算符是solidity中唯一一个接收三个操作数的运算符,规则条件?条件真表达式:条件假表达式。 //三元运算符 function ternaryTest(uint256 x, uint256 y) public pure returns(uint256) { return x >= y ? x : y; } 另外患有continue和break关键字可以使用。 用solidity实现插入排序 //插入排序 错误版 function insertionSortWrong(uint[] memory a) public pure returns(uint[] memory) { for(uint i = 1; i < a.length; i++) { uint temp = a[i]; uint j = i - 1; while((j > 0) && (temp < a[i])) { a[j + 1] = a[j]; j--; } a[j+1] = temp; } return a; } //插入排序,正确版 function insertionSort(uint[] memory a) public pure returns(uint[] memory) { for(uint i = 1; i < a.length; i++) { uint temp = a[i]; uint j = i; while((j >= 1) && (temp < a[j - 1])) { a[j] = a[j - 1]; j--; } a[j] = temp; } return a; } ## Publication Information - [startha](https://paragraph.com/@starha/): Publication homepage - [All Posts](https://paragraph.com/@starha/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@starha): Subscribe to updates