By bubbling learn how recursion

bubble

Foreword

I come from a good friend EvilSay posting, the following is the original:

Bubble sort, I believe we hear the words were all very simple, and I think it is, but it can not be more simple? For example, implemented using recursion.

Ordinary bubble

public static int[] bubblerecursion (int array[]) {
    for (int i = 0;i < array.length - 1; i ++) {
        for (int j = i + 1;j < array.length;j ++) {
            if (array[j] < array[i]) {
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
    return array;
}

Common implementations bubble sort codes as shown above, two loop for determining if a +. Not to mention the amount of code of the problem, but on this readability to put people sick. Let's look delightful is how to achieve recursive bubbling.

Recursive bubbling

public int[] bubblerecursion(int[] nums){

  // step 1
  for (int i = 0; i < nums.length-1; i++) { 
    // step 2
    if(nums[i + 1] < nums[i] ){

      int tmp = nums[i+ 1];

      nums[i+ 1] = nums[i];

      nums[i] = tmp;
      // step 3
      return bubblerecursion(nums);
    }
  }
  // step 4
  return nums;
}
整段代码分为 4 部分,放入 Int 数组 nums = {1, 6, 2}
step 1

The first step is a recursive boundary, completing the cycle when it loops back to the first layer of either value, or terminate the entire call itself and returns the value of the final processing, when the code to run the first step: i = 0, i is less than the array length minus 1, i ++

step 2

The i-th bit in the array determines the i + 1-bit, if the array is true for the exchange and to the position of the third step, the first for loop and if false proceeds to enter the fourth step after the for loop.

Note: If step2 condition is true, then there is no need to enter the step 4.

step 3

This is the most winding step, forming a code that calls itself recursively. We can see that the parameters, if the code execution to step 3 into the parameters that now becomes nums [1,2,6]. And open a new cycle in step3 time.

NOTE: At this point in the code equals step3 stopped and waits for a new cycle value came, receives the value transmitted from the final loop and terminating calls itself the result returned to the caller.

Combat: to solve the problem LeetCode No. 203: Using recursive delete all nodes equal to a given value of val list.

/** 第203号问题链表的实现
 * @Author: EvilSay
 * @Date: 2019/7/31 23:15
 */
public class ListNote {
    public int val;
    public ListNote next;

    public ListNote(int x){
        val = x;
    }
    //链表节点的构造函数
    //使用arr为参数,创建一个链表,当前ListNote为链表头节点
    public ListNote(int[] arr){
        if (arr == null || arr.length == 0)
            throw new IllegalArgumentException("arr can not be empty");

        this.val = arr[0];
        //通过访问构造方法获取cur的第0个参数位置
        ListNote cur = this;
        for (int i = 1; i <arr.length ; i++) {
            //为下一个节点创建新的空间
            cur.next = new ListNote(arr[i]);
            //为下一位节点赋值
            cur = cur.next;
        }
    }
    //以当前节点为头节点的链表信息字符串
    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        ListNote cur = this;
        while (cur != null){
            res.append(cur.val + "->");
            cur = cur.next;
        }
        res.append("NULL");
        return res.toString();
    }
}
//普通解法
    public ListNode removeElements(ListNode head,int val){
        
        while (head != null && head.val == val){
            
            head = head.next;
        }

        if (head == null)
            return null;
        ListNode prev = head;
        //检查下一个节点是否需要删除
        while (prev.next != null){
            //prev下一个节点如果等于要删除的节点
            if (prev.next.val == val)
                //则下一个节点等于下下个节点
                prev.next = prev.next.next;
            else
                prev = prev.next;
        }
        return head;
    }
//递归解法
    public ListNote removeElements(ListNote head,int val){
        if (head == null)
            return null;
       head.next = removeElements(head.next,val);

        return head.val == val ? head.next : head;
    }

Be sure to read the code in numerical order

模拟调用6->7->null删除元素7

1: 代码运行到第一步:the node is empty acquired (the current node 6) returns to the Null layer of recursion, if any.

2: 代码运行到第二步:(current node 6) of the current node is equal to one heade.next == 7and the incoming node recursion

3: Enter the recursive call, and return to 代码运行第一步(the current node 6)

4: 代码运行到第一步:the node is empty acquired (the current node 7) on the layer returns to the Null recursion.

5: 代码运行到第二步:(current node 7) Under the current node is equal to one heade.next == nulland the incoming node recursion

6: enter recursive calls, and return to 代码运行第一步(the current node is null)

7: 代码运行到第一步:the node is empty acquired (the current node is null) returns to the Null layer of recursion.

8: 代码运行到第三步:to determine whether the current node is equal to the node to be removed if the node is equal to the level of recursion came returns, if not equal to the current node is returned, (return to the node level recursive coming)

9: 代码运行到第三步:to determine whether the node is equal to the current node to be removed if the node is equal to the level of recursion came returns, if not equal to the current node is returned, (return to the current node)

Afterword

Comparing the two, I think the bubble recursive code simplicity, readability advantage. For friend no basis for the algorithm, new to recursion, may feel a bit around, this is normal. Algorithm is a very magical knowledge, it is difficult, interesting, often learned such things, make you a lifetime.

Recommended Reading

java | What is a dynamic proxy?

SpringBoot | log is how to achieve?

SpringBoot | is how to achieve automatic configuration?

At last

If you see here, like this article, please forward, thumbs up. Micro-channel search " a good basket case ", welcome attention.

Reply to " 1024 " will give you a complete set of java, python, c ++, go , front-end, linux, algorithms, large data, artificial intelligence, applets, and English tutorials.

Reply " e-book " 50 + to send you this e-book java.

Programming language

A good basket

Guess you like

Origin www.cnblogs.com/nasus/p/12206124.html