Original title: "Introduction to Solidity Minimalist: 7. Control flow, use solidity to implement insertion sorting"
Original author: 0xAA
I am re-learning solidity recently, to consolidate the details, and also write a "Solidity minimalist introduction" for use by novices (Programmers can find another tutorial), 1-3 lectures are updated every week.
All codes are open source on github: github.com/AmazingAng/ WTFSolidity
In this lecture, we will introduce the control flow in solidity, and then talk about how to use solidity to implement insertion sort (InsertionSort), a seemingly simple, but practical It is easy to write buggy programs.
Solidity's control flow is similar to other languages, mainly including the following :

< br>




In addition, there are continue (immediately enter the next cycle) and The break (out of the current loop) keyword can be used.
Written in the front: more than 90% People who use solidity to write insertion algorithms will make mistakes.
The sorting algorithm solves the problem of An unordered set of numbers, such as [2, 5, 3, 1], is arranged in order from small to large. Insertion sort (InsertionSort) is the simplest sorting algorithm, and it is also the first algorithm that many people learn. Its idea is very simple. From front to back, compare each number with the number in front of it in turn. If it is smaller than the number in front of it, swap the positions. Diagram:

insertion sort  ;
We can first look at the python code of insertion sort: p>
There is a bug after rewriting to solidity!
A total of 8 lines of python code can complete the insertion sort, which is very simple. Then we rewrite it into solidity code, convert functions, variables, loops, etc., and only need 9 lines of code:

Then let's put the modified one on the remix and run it, input [2, 5, 3, 1]. BOOM! There are bugs! After changing it for a long time, I couldn't find where the bug is. I went to Google to search for "solidity insertion sort", and found that the insertion algorithm tutorials written in solidity on the Internet are all wrong, for example: Sorting in Solidity without Comparison
Spent several hours, with the help of a friend in the Dapp-Learning community, I finally found the bug. The most commonly used variable type in solidity is uint, which is a positive integer. If a negative value is obtained, an underflow error will be reported. In the insertion algorithm, the variable j may take -1, causing an error.
Here, we need to add 1 to j so that it cannot take negative values. Correct code:

The result after running:

Original link
Welcome to join the official BlockBeats community:
Telegram Subscription Group: https://t.me/theblockbeats
Telegram Discussion Group: https://t.me/BlockBeats_App
Official Twitter Account: https://twitter.com/BlockBeatsAsia

