A complete set of in-depth exploration of Java arrays - advanced knowledge stage 3, sort natural sorting

A complete set of in-depth exploration of Java arrays - advanced knowledge stage 3, sort natural sorting


Table of contents

The importance of array learning

sortNatural sorting

Example - the system comes with natural sorting

Example - Custom natural sorting (you can see it yourself, the content involved here is beyond the current scope)

Compare selection sort, bubble sort, natural sort

Selection Sort:

Bubble Sort:

Natural Sort:

Summarize:


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!

sortNatural sorting

Natural Sort is an algorithm that sorts elements according to their natural order. It is often used to sort arrays containing text data so that the elements are in human-readable order. The specific process of the natural sorting algorithm is as follows:

First, adjacent elements in the array are compared.

If adjacent elements are not in the correct natural order (for example, alphabetically or numerically), their positions are swapped.

Continue to traverse the array, repeating the above comparison and exchange operations until the entire array is arranged in natural order.

Example:

Consider the following string array to be sorted: ["file10.txt", "file1.txt", "file2.txt", "file20.txt", "file3.txt"]

The process of sorting an array using natural ordering is as follows:

Round 1:

Compare "file10.txt" .txt"]

Compare "file10.txt" and "file2.txt" without exchanging positions.

Compare "file20.txt" .txt"]

Compare "file20.txt" and "file3.txt" without exchanging positions.

Round 2:

Exclude the last sorted element "file3.txt" and continue comparing the previous elements.

Compare "file10.txt" .txt"]

...(and so on)


Repeat the above steps until the entire array is sorted. The final sorted array is: ["file1.txt", "file2.txt", "file3.txt", "file10.txt", "file20.txt"]

By using natural ordering, we get a list of file names in natural order. Note that natural ordering does not sort based on simple character encoding, but takes into account human-readable ordering, such as "file2.txt" before "file10.txt" and "file10.txt" Ranked before "file20.txt". This makes the sorting results more consistent with human expectations and understanding.

Example - the system comes with natural sorting

The following is sample code for natural sorting of an array [64, 34, 25, 12, 22, 11, 90] using Java language, with comments:

import java.util.Arrays;

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();
        // 使用自定义的比较器进行自然排序
        Arrays.sort(arr);

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

Example - Custom natural sorting (you can see it yourself, the content involved here is beyond the current scope)

import java.util.Arrays;
import java.util.Comparator;

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();
        // 将整型数组转换为字符串数组,以便进行自然排序
        String[] strArr = Arrays.stream(arr)
                .mapToObj(Integer::toString)
                .toArray(String[]::new);
        
        // 使用自定义的比较器进行自然排序
        Arrays.sort(strArr, new NaturalComparator());
        
        // 打印排序后的数组
        System.out.println("排序后的数组:");
        for (String str : strArr) {
            System.out.print(Integer.parseInt(str) + " ");
        }
    }
}

// 自定义比较器实现自然排序
class NaturalComparator implements Comparator<String> {
    @Override
    public int compare(String str1, String str2) {
        int idx1 = 0, idx2 = 0;
        int len1 = str1.length(), len2 = str2.length();
        int minLen = Math.min(len1, len2);
        char c1=' ', c2=' ';
        int result;
        
        while (idx1 < minLen && (c1 = str1.charAt(idx1)) == (c2 = str2.charAt(idx2))) {
            if (Character.isDigit(c1) && Character.isDigit(c2)) {
                // 如果当前字符是数字,则比较整数值
                int val1 = Integer.parseInt(str1.substring(idx1));
                int val2 = Integer.parseInt(str2.substring(idx2));
                result = Integer.compare(val1, val2);
                if (result != 0) {
                    return result;
                } else {
                    // 如果整数值相等,则比较整数的长度,长度较长的字符串应排在后面
                    int digitLen1 = str1.length() - idx1;
                    int digitLen2 = str2.length() - idx2;
                    result = Integer.compare(digitLen1, digitLen2);
                    if (result != 0) {
                        return result;
                    }
                }
            }
            idx1++;
            idx2++;
        }
        // 如果字符串的前缀相同但长度不同,则较短的字符串应排在前面
        if (idx1 == minLen) {
            return str2.charAt(idx2) == '0' ? 0 : -1;
        } else if (idx2 == minLen) {
            return str1.charAt(idx1) == '0' ? 0 : 1;
        } else {
            // 比较剩余部分的字符值
            return Character.compare(c1, c2);
        }
    }
}

Compare selection sort, bubble sort, natural sort

Selection sort, bubble sort and natural sort are three common sorting algorithms, and there are some differences and characteristics between them.

Selection Sort:

Basic idea: Find the smallest (or largest) element in the unsorted sequence, store it at the beginning of the sorted sequence, then continue to find the smallest (or largest) element from the remaining unsorted elements, and then put it at the end of the sorted sequence. . And so on until all elements are sorted.

Time complexity: The time complexity of selection sort is O(n^2), where n is the length of the sequence to be sorted. This is because every time you need to find the smallest (or largest) element in the unsorted sequence, n-1 comparison and swap operations are required.

Space Complexity: The space complexity of selection sort is O(1) because it only requires an additional storage space for temporary storage of the smallest (or largest) element.

Bubble Sort:

The basic idea: Through comparison and exchange between adjacent elements, the largest (or smallest) element in each round of sorting "bubbles" to one end of the sequence. Repeat multiple rounds of sorting until the entire sequence is in order.

Time complexity: The time complexity of bubble sort is O(n^2), where n is the length of the sequence to be sorted. In the worst case, n-1 rounds of compare and swap operations are required.

Space complexity: The space complexity of bubble sort is O(1) because it only requires an extra storage space for temporary storage of swapped elements.

Natural Sort:

Basic idea: Sort according to the natural order of elements. For example, strings can be sorted in alphabetical order, and numbers can be sorted in numerical order. Natural sorting is often used when dealing with mixed types of data, such as mixed lists of strings and numbers.

Time complexity: The time complexity of natural sort depends on the implementation, but is usually O(n^2) or higher. Because natural sorting requires comparison and conversion of different types of data, it is more complex than selection sorting and bubble sorting.

Space complexity: The space complexity of natural sort also depends on the specific implementation, but is usually O(1) or higher. Additional storage space may be required to store converted data or perform other operations.


Summarize:

Selection sort, bubble sort and natural sort are simple sorting algorithms suitable for sorting small-scale data.

The time complexity and space complexity of selection sort and bubble sort are both O(n^2) and O(1), but they differ in implementation and exchange operations.

Natural sorting is suitable for processing mixed types of data, but the implementation is relatively complex, and the time complexity and space complexity may be high.

Guess you like

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