search
HomeJavajavaTutorialJava implementation of sorting algorithms: insertion sort, selection sort, bubble sort

package sort;
  
/**
 * @author lei 2011-8-17
 */
public class Sort {
  
    /**
     * 选择排序: 
     * 首先在数组中查找最小值, 如果该值不在第一个位置, 那么将其和处在第一个位置的元素交换,然后从第二个位置重复
     * 此过程,将剩下元素中最小值交换到第二个位置 。当到最后一位 时,数组排序结束 
     * 复杂度为:O(n^2)
     * 
     * @param array
     */
    static void selectionSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            int min_idx = i;
  
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[min_idx]) {
                    min_idx = j;
                }
            }
  
            if (min_idx != i) {
                swap(array, min_idx, i);
            }
  
        }
    }
  
    /**
     * 冒泡排序法: 
     * 是运用数据值比较后,依判断规则对数据位置进行交换,以达到排序的目的 
     * 复杂度都是O(n^2)
     * 
     * @param array
     */
    public static void bubbleSort(int[] array) {// 冒泡排序算法
        int out, in;
        // 外循环记录冒泡次数
        for (out = array.length - 1; out >= 1; out--) {
            boolean flag = false;
            // 进行冒泡
            for (in = 0; in < out; in++) {
                // 交换数据
                if (array[in] > array[in + 1]) {
                    swap(array, in, in + 1);
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
  
        }
    }
  
    /**
     * 插入排序 
     * 是对于欲排序的元素以插入的方式寻找该元素的适当位置,以达到排序的目的。 
     * 插入排序的最差和平均情况的性能是O(n^2)
     * 
     * @param array
     */
    public static void insertSort(int[] array) {// 插入排序算法
        int in, out;
        for (out = 1; out < array.length; out++) {// 外循环是给每个数据循环
            int temp = array[out]; // 先取出来保存到临时变量里
            in = out; // in是记录插入数据之前的每个数据下标
            // while内循环是找插入数据的位置,并且把该位置之后的数据(包括该位置)
            // 依次往后顺移。
            while (in > 0 && array[in - 1] >= temp) {
                array[in] = array[in - 1]; // 往后顺移
                --in; // 继续往前搜索
            }
            array[in] = temp; // 该数据要插入的位置
        }
    }
  
    /**
     * 交换数组数据
     * 
     * @param array
     * @param min_idx
     * @param i
     */
    private static void swap(int[] array, int min_idx, int i) {
        int temp = array[min_idx];
        array[min_idx] = array[i];
        array[i] = temp;
    }
  
    public static void main(String[] args) {
  
        int[] array = new int[] { 1, 2, 6, 5, 7, 9, 0, 121, 4545 };
        bubbleSort(array);
        for (int i : array) {
            System.out.println(i);
        }
  
    }
  
}

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Explain the difference between platform independence and cross-platform development.Explain the difference between platform independence and cross-platform development.Apr 26, 2025 am 12:08 AM

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?Apr 26, 2025 am 12:02 AM

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools