Java Data Structures and Algorithms - Bubble Sort

1. About sorting

Sorting, also known as Sort Algorithm, is the process of arranging a set of data in a specified order.

Sort by category:

  1. Internal sorting: Refers to loading all data to be processed into internal memory for sorting.
  2. External sorting method: The amount of data is too large to be fully loaded into memory, and external storage is required for sorting.


2. Code Case

The basic idea of ​​Bubble Sorting is: by treating the sorted sequence from front to back (starting from the element with the smaller subscript), compare the values ​​of adjacent elements in turn, and if the reverse order is found, exchange them to make the element with the larger value Gradually move from the front to the back, rising up like bubbles under the water. 

Because in the process of sorting, each element is constantly approaching its own position. If there is no exchange after a comparison, it means that the sequence is in order. Therefore, a flag should be set in the sorting process to determine whether the elements have been exchanged. Thereby reducing unnecessary comparisons.

package com.szh.sort;

import java.util.Arrays;

/**
 *
 */
public class BubbleSort {

    private static void bubbleSort(int[] arr) {
        int temp = 0; //临时变量
        boolean flag = false; //标记变量,表示是否进行过两个数的交换(用来优化冒泡排序)
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                //如果前面的数比后面的数大,则交换
                if (arr[j] > arr[j + 1]) {
                    flag = true; //有两个数交换过,将标记变量置为true
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
            if (!flag) { //在一趟排序中,一次交换都没有发生过,则说明数组已经有序,无需再进行后续的排序工作
                break;
            } else {
                flag = false; //重置flag!!!, 进行下次判断
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 9, -1, 10, 20};

        System.out.println("排序前:");
		System.out.println(Arrays.toString(arr));

        //测试冒泡排序
        bubbleSort(arr);

        System.out.println("排序后:");
        System.out.println(Arrays.toString(arr));
    }
}


3. Comparison of various sorting algorithms

Guess you like

Origin blog.csdn.net/weixin_43823808/article/details/123529429