Sorting algorithm practice-bubble sort and quick sort template

This article compares bubble sort and quick sort

One, bubble sort

  1. algorithm
//对数组nums的索引i + 1 ~ nums.length - 1 数组元素进行排序
  for(int m = i + 1; m < nums.length; m++){
    
    
      for(int n = nums.length - 1; n > m; n--){
    
    
          if(nums[n] < nums[n - 1]){
    
    
              tmp = nums[n - 1];
              nums[n - 1] = nums[n];
              nums[n] = tmp;
          }
      }
  }
  1. Description
    a. The outer layer m will be one less each time, which is used to limit the number of the inner layer loop each time
    b. The outer layer is increasing, and the inner layer is decreasing.

Two, quick sort

  1. algorithm
private void quickSort(int[] nums, int from, int to){
    
    
    //结束条件
    if(from >= to){
    
    
        return;
    }

    //以第一个为中轴点分开为两个数组
    int left = from, right = to;
    int midVal = nums[from];
    int round = 2;//1表示左侧判断,1表示右侧判断
    while(left < right){
    
    
        if(round == 1){
    
    
            if(nums[left] <= midVal){
    
    
                left++;
            }else{
    
    
                nums[right] = nums[left];
                right--;
                round = 2;
            }
        }else if(round == 2){
    
    
            if(nums[right] >= midVal){
    
    
                right--;
            }else{
    
    
                nums[left] = nums[right];
                left++;
                round = 1;
            }
        }
    }
    nums[left] = midVal;

    //递归
    quickSort(nums, from, left - 1);
    quickSort(nums, left + 1, to);
}
  1. Description
    a. Recursively realize quick sort
    b. Refer to https://blog.csdn.net/qq_40285839/article/details/83018673

Guess you like

Origin blog.csdn.net/hudmhacker/article/details/107709706