search
HomeJavajavaTutorialHow to implement simple sorting in Java

    Sorting is a very common and core operation in data processing. Although there is a small chance that we will need to implement it manually in actual project development, after all, there are classes in each language’s class library. There are many implementations of sorting algorithms. But it is still of great benefit to us to understand these subtle ideas. This article briefly reviews the three most basic types of algorithms: selection, bubbling, and insertion.

    First define a function to exchange array elements, which can be called when sorting

    /**
         * 交换数组元素
         * @param arr
         * @param a
         * @param b
         */
        public static void swap(int []arr,int a,int b){
            arr[a] = arr[a]+arr[b];
            arr[b] = arr[a]-arr[b];
            arr[a] = arr[a]-arr[b];
        }

    Simple selection sorting

    Simple selection sorting is the simplest and most intuitive algorithm. The basic idea is Each pass selects the smallest (or largest) element from the data elements to be sorted as the first element until all elements are sorted. Simple selection sorting is an unstable sorting.

    When the algorithm is implemented, each time the minimum element is determined, the first position will be the current minimum through constant comparison and exchange. Exchange is a relatively time-consuming operation. In fact, we can easily find that these exchanges are meaningless before the current minimum element is completely determined. We can set a variable min to store only the array subscript of the smaller element for each comparison. When the loop ends, this variable stores the subscript of the current smallest element, and then perform the exchange operation. The code implementation is very simple, let’s take a look.

    Code implementation

    /**
         * 简单选择排序
         *
         * @param arr
         */
        public static void selectSort(int[] arr) {
            for (int i = 0; i < arr.length - 1; i++) {
                int min = i;//每一趟循环比较时,min用于存放较小元素的数组下标,这样当前批次比较完毕最终存放的就是此趟内最小的元素的下标,避免每次遇到较小元素都要进行交换。
                for (int j = i + 1; j < arr.length; j++) {
                    if (arr[j] < arr[min]) {
                        min = j;
                    }
                }
                //进行交换,如果min发生变化,则进行交换
                if (min != i) {
                    swap(arr,min,i);
                }
            }
        }

    After simple selection sorting is optimized above, the number of comparisons remains unchanged regardless of the original arrangement of the array; for exchange operations, in the best case, the array is completely When the array is in reverse order, there is no need for any exchange moves. In the worst case, that is, when the array is in reverse order, the number of exchanges is n-1. Taken together, the time complexity is O(n2)

    Bubble sort

    The basic idea of ​​bubble sort is to compare adjacent elements pairwise, and exchange them if the order is reversed. In this way, each pass will "float" the smallest or largest element to the top, and finally achieve complete order

    How to implement simple sorting in Java

    Code implementation

    In bubble sort During the process, if a certain trip is completed without any exchange operation, for example, the array [5,4,1,2,3] performs bubbling twice, that is, after two outer loops, 5 and 4 are adjusted to the final position [1,2,3,4,5]. At this time, after executing the third loop, no exchange has been done, which means that the remaining sequences are already in order, and the sorting operation can be completed. Let’s take a look at the code

    /**
         * 冒泡排序
         *
         * @param arr
         */
        public static void bubbleSort(int[] arr) {
            for (int i = 0; i < arr.length - 1; i++) {
                boolean flag = true;//设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已然完成。
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    if (arr[j] > arr[j + 1]) {
                        swap(arr,j,j+1);
                        flag = false;
                    }
                }
                if (flag) {
                    break;
                }
            }
        }

    according to The above bubble implementation, if the original array itself is ordered (this is the best case), can be completed with only n-1 comparisons; if it is in reverse order, the number of comparisons is n-1 n-2 ... 1= n(n-1)/2, the number of exchanges and the number of comparisons are equal. Therefore, its time complexity is still O(n2). Overall, the performance of bubble sort is still slightly worse than the selection sort above.

    Direct insertion sorting

    The basic idea of ​​direct insertion sorting is to insert a record to be sorted into the previously sorted sequence at each step until all elements have been inserted. .

    How to implement simple sorting in Java

    Code implementation

    /**
         * 插入排序
         *
         * @param arr
         */
        public static void insertionSort(int[] arr) {
            for (int i = 1; i < arr.length; i++) {
                int j = i;
                while (j > 0 && arr[j] < arr[j - 1]) {
                    swap(arr,j,j-1);
                    j--;
                }
            }
        }

    In the best case, simple insertion sort needs to be compared n-1 times without exchanging elements, and the time complexity is O( n); In the worst case, the time complexity is still O(n2). But when the array elements are randomly arranged, insertion sort is still better than the above two sorts.

    The above is the detailed content of How to implement simple sorting in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software