# 控制流和插入排序

By [startha](https://paragraph.com/@starha) · 2023-09-22

---

[控制流](https://github.com/starthapro/starha_solidity/tree/main/09_InsertionSort#%E6%8E%A7%E5%88%B6%E6%B5%81)
-----------------------------------------------------------------------------------------------------------

`solidity`的控制流与其他语言类似，主要包括一下集中：

1.  `if-else`
    

        //if-else
        function ifElseTest(uint256 _number) public pure returns(bool) {
            if(_number == 0) {
                return true;
            } else {
                return false;
            }
        }
    

1.  `for`
    

        //for
        function forLoopTest() public pure returns(uint256) {
            uint sum = 0;
            for(uint i = 0; i < 10; i++) {
                sum += i;
            }
    
            return sum;
        }
    

1.  `while`
    

        //while
        function whileTest() public pure returns(uint256) {
            uint sum = 0;
            uint i = 0;
            while(i < 10) {
                sum += i;
                i++;
            }
    
            return sum;
        }
    

1.  `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;
        }
    

1.  `三元运算符`是solidity中唯一一个接收三个操作数的运算符，规则`条件？条件真表达式：条件假表达式`。
    

        //三元运算符
        function ternaryTest(uint256 x, uint256 y) public pure returns(uint256) {
            return x >= y ? x : y;
        }
    

另外患有`continue`和`break`关键字可以使用。

[用solidity实现插入排序](https://github.com/starthapro/starha_solidity/tree/main/09_InsertionSort#%E7%94%A8solidity%E5%AE%9E%E7%8E%B0%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------

         //插入排序 错误版
        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;
            
        }

---

*Originally published on [startha](https://paragraph.com/@starha/V0AHROpwTzoNj68q5dJ2)*
