Talking about Flutter Dart Quick Sort Algorithm Example

 

In the process of daily research and development, we are always considering whether the programs we develop are efficient. A good program execution is inseparable from a deep understanding and mastery of algorithms. In the days to come, I will take everyone to review several common algorithms.

Let's learn about  the quick sort algorithm together  !

quick sort algorithm

Wikipedia introduction: Quick sort uses the divide and conquer strategy to divide a sequence (list) into two smaller and larger subsequences, then recursively sort the two subsequences, and finally merge to get a list from small to large the sequence of.

Smart friends will ask: What is the divide and conquer strategy?

Divide and conquer

The literal explanation is "divide and conquer", which is to divide a complex problem into two or more identical or similar sub-problems, and then divide the sub-problems into smaller sub-problems... until the last sub-problem can be solved simply and directly , the solution of the original problem is the combination of the solutions of the subproblems.

From this we can lead to the implementation steps of the quick sort algorithm we are talking about today :

  • Obtain a value randomly from the data, and divide it into two data sets on the left and right according to the size of this value. The value of the data set on the left is smaller than this value, and vice versa
  • Recursively call the data on both sides Step 1
  • Combine all data

Quick sort algorithm implementation

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

void main() {

  List<int> quickSort(List<int> arr) {

    // 处理边界问题

    if (arr.length <= 1) {

      return arr;

    }

    // 取出第一个值作为参考

    int splitData = arr[0];

    // 小于参考值的集合

    List<int> low = [];

    // 大于参考值的集合

    List<int> hight = [];

    // 与参考相等的集合

    List<int> mid = [];

    // 初次把参考值添加到mid中

    mid.add(splitData);

    for (int i = 1; i < arr.length; i++) {

      if (arr[i] < splitData) {

        // 小于

        low.add(arr[i]);

      } else if (arr[i] > splitData) {

        // 大于

        hight.add(arr[i]);

      } else {

        // 等于

        mid.add(arr[i]);

      }

    }

    // 二分数据后,再继续递归整理

    low = quickSort(low);

    hight = quickSort(hight);

    // 最后合并

    return [...low, ...mid, ...hight];

  }

  const List<int> ary = [4, 5, 1, 3, 6, 2, 5, 6, 7, 2, 4];

  print(quickSort(ary));

}

So far, we have revisited the  quick sort algorithm  !

 

Reposted from: Micro reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131864566
Recommended