A complete set of in-depth exploration of Java arrays - advanced knowledge stage 2, bubble sorting

A complete set of in-depth exploration of Java arrays - advanced knowledge stage 2, bubble sorting


Table of contents

The importance of array learning

The specific sorting process of bubble sort

Comparison of selection sort and bubble sort

Method to realize:

time complexity:

Space complexity:

stability:

Comparing data (taking the array [64, 34, 25, 12, 22, 11, 90] as an example):


General article link:https://laoshifu.blog.csdn.net/article/details/134906408

The importance of array learning

Arrays are one of the data structures that we must master, and they will be of great help to us in the future.

  • Improve program efficiency: Array is an efficient data structure that can quickly access and modify data. In actual production and life, arrays are widely used in various scenarios that require efficient data processing, such as image processing, scientific computing, financial analysis, etc. By learning arrays, students can process data more efficiently and improve program execution efficiency.
  • Enhance programming abilities: Arrays are one of the commonly used data structures in programming. Mastering the use of arrays is very important for students to improve their programming abilities. In the actual programming process, the use of arrays is very common. Mastering the use of arrays can help students become more proficient in programming and improve programming efficiency and code quality.
  • Cultivate logical thinking: Array is an abstract data structure. By learning arrays, students can develop their logical thinking abilities. In actual problem solving, many problems can be transformed into array processing problems. By learning arrays, students can think about problems more clearly and come up with effective solutions.

Learning arrays can be a somewhat difficult task for students, but if you keep studying, you can master it. Here are some words of encouragement for students learning about arrays:

  • Arrays are the basis of programming, and mastering the use of arrays is very important to becoming a good programmer.
  • Learning arrays can be difficult, but if you stick with it, you'll be able to master it.
  • By learning arrays, you can process data more efficiently, improve program execution efficiency, and show your programming abilities.
  • Arrays are widely used. Mastering the use of arrays can make you better in your future study and work.
  • Believe in yourself, you will be able to master the use of arrays and become an excellent programmer!

The specific sorting process of bubble sort

Bubble Sort is a simple sorting algorithm. Its basic idea is to continuously exchange adjacent unsorted elements so that the largest (or smallest) element in each round of sorting "bubbles" to one end of the array. The specific sorting process is as follows:

  1. Starting from the first element of the array, compare two adjacent elements.
  2. If the first element is larger than the second (or swapping is required depending on the sort order), swap their positions.
  3. Continue comparing the next pair of adjacent elements, performing the same operation, until the end of the array.
  4. After the first round of comparisons and swaps, the largest element is moved to the end of the array (or the last position according to the sort order).
  5. Repeat the above steps, but exclude the last sorted element each time, until the entire array is sorted.
public class Demo1 {
    public static void main(String[] args) {
        // 定义待排序的数组
        int[] arr = { 64, 34, 25, 12, 22, 11, 90 };

        // 打印排序前的数组
        System.out.println("排序前的数组:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();

        // 执行选择排序算法
        int n = arr.length;

        // 遍历数组,进行n-1轮比较和交换
        for (int i = 0; i < n - 1; i++) {
            // 找到当前未排序部分中的最小元素索引
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // 将找到的最小元素与未排序部分的第一个元素交换位置
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
        // 打印排序后的数组
        System.out.println("排序后的数组:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Example:
Consider the following array to be sorted [64, 34, 25, 12, 22, 11, 90]

Round 1:
Compare 64 and 34, swap positions: [34, 64, 25, 12, 22, 11, 90]
Compare 64 and 25, swap positions: [34, 25, 64, 12, 22, 11, 90]
Compare 64 and 12, swap positions: [34, 25, 12, 64, 22 , 11, 90]
Compare 64 and 22, swap positions: [34, 25, 12, 22, 64, 11, 90]
Compare 64 and 11 , exchange positions: [34, 25, 12, 22, 11, 64, 90]
Compare 64 and 90, do not exchange positions: [34, 25, 12, 22, 11, 64, 90]

Round 2:
Exclude the last sorted element 90 and continue to compare the previous elements.
Compare 34 and 25, exchange positions: [25, 34, 12, 22, 11, 64, 90]
... (and so on) < /span>

Repeat the above steps until the entire array is sorted. The final sorted array is [11, 12, 22, 25, 34, 64, 90].

Through multiple rounds of comparison and exchange operations, bubble sorting gradually "bubbles" the largest element to one end of the array, thereby sorting the entire array.

Comparison of selection sort and bubble sort

Selection sort and bubble sort are both simple sorting algorithms. They have some differences in implementation and have different performance characteristics in some aspects. Here's how they compare:

Time complexity, space complexity, algorithm stability description and examples-CSDN Blog

Method to realize:

Selection sort: Find the smallest (or largest) element in the unsorted part in each round and exchange it with the first element of the unsorted part until the entire array is sorted.

Bubble sorting: Through the comparison and exchange of adjacent elements, the largest (or smallest) element in each round of sorting "bubbles" to one end of the array until the entire array is sorted.

time complexity:

The time complexity of selection sort is O(n^2), where n is the size of the array. Because no matter whether the array is sorted or not, n-1 rounds of comparison and exchange operations are required.

The time complexity of bubble sort is also O(n^2). But in the best case, when the array is already sorted, bubble sort can be terminated early and the time complexity can reach O(n). However, in worst and average cases, bubble sort has more comparisons and swaps.

Space complexity:

The space complexity of both selection sort and bubble sort is O(1) because they only require a constant level of extra space to store temporary variables.

stability:

Selection sort is an unstable sorting algorithm because swap operations may change the relative order of equal elements.

Bubble sort is a stable sorting algorithm because the relative order between equal elements does not change during the sorting process.

Comparing data (taking the array [64, 34, 25, 12, 22, 11, 90] as an example):

The number of comparisons in selection sorting: The number of comparisons required in each round gradually decreases, and a total of (n-1) + (n-2) + ... + 1 = n*(n-1)/2 comparisons are required. In this example, a total of 21 comparisons are required.

The number of comparisons of bubble sorting: In the worst case, the number of comparisons required is the same as that of selection sorting, that is, n*(n-1)/2 comparisons. However, if the array is already sorted, only n-1 comparisons need to be made. In this example, the first round requires 6 comparisons, the second round requires 5 comparisons, and so on, for a total of 21 comparisons.

The number of exchanges in selection sorting: at most one exchange per round, and a total of n-1 exchanges at most. In this example, a total of 6 exchanges are required.

Number of exchanges for bubble sort: In the worst case, the number of exchanges required is the same as that of selection sort, that is, n-1 exchanges. However, if the array is already sorted, no swapping is required. In this example, 5 exchanges are required in the first round, 3 exchanges are required in the second round, and so on, for a total of 15 exchanges.

To sum up, the time complexity of selection sort and bubble sort is both O(n^2), but they are different in implementation, stability, and specific number of comparisons and exchanges. Selection sorting finds the smallest (or largest) element and exchanges it in each round, which is simple but unstable; while bubble sorting "bubbles" out the largest (or smallest) element by comparing and exchanging adjacent elements, which achieves slightly better results. Complex but stable. In practical applications, choosing an appropriate sorting algorithm depends on specific needs and data set characteristics.

Guess you like

Origin blog.csdn.net/feng8403000/article/details/134909628