Home Java javaTutorial What are the sequential sorting methods?

What are the sequential sorting methods?

Jul 23, 2019 pm 02:54 PM
java sort

What are the sequential sorting methods?

Recommended tutorial: java tutorial

In computer science and mathematics, a Sorting algorithm (English: Sorting algorithm) is an algorithm that can arrange a series of data according to a specific sorting method. This article will summarize several commonly used sorting algorithms, including bubble sort, selection sort, insertion sort, quick sort and merge sort.

1. Bubble sort

Principle diagram

What are the sequential sorting methods?

Understanding: By repeatedly iterating through the list to be sorted, comparing each pair of adjacent items, and swapping them if they are in the wrong order.

Code:

public class BubbleSort {
  
    // logic to sort the elements
    public static void bubble_srt(int array[]) {        int n = array.length;        int k;        for (int m = n; m >= 0; m--) {            for (int i = 0; i < n - 1; i++) {
                k = i + 1;                if (array[i] > array[k]) {
                    swapNumbers(i, k, array);
                }
            }
            printNumbers(array);
        }
    }  
    private static void swapNumbers(int i, int j, int[] array) {  
        int temp;
        temp = array[i];        array[i] = array[j];        array[j] = temp;
    }  
    private static void printNumbers(int[] input) {          
        for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
    }  
    public static void main(String[] args) {        int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
        bubble_srt(input);
    }
}
Copy after login

2. Selection sort

Principle Figure

What are the sequential sorting methods?

Understanding: The inner loop finds the next minimum (or maximum) value, and the outer loop puts the value into its proper location.

Code:

public class SelectionSort { 
    public static int[] doSelectionSort(int[] arr){         
        for (int i = 0; i < arr.length - 1; i++)
        {            int index = i;            for (int j = i + 1; j < arr.length; j++)                if (arr[j] < arr[index]) 
                    index = j;      
            int smallerNumber = arr[index];  
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }        return arr;
    }     
    public static void main(String a[]){         
        int[] arr1 = {10,34,2,56,7,67,88,42};        int[] arr2 = doSelectionSort(arr1);        for(int i:arr2){
            System.out.print(i);
            System.out.print(", ");
        }
    }
}
Copy after login

3. Insertion sort

Principle Figure

What are the sequential sorting methods?

Understanding: Each step inserts a record to be sorted into the previously sorted sequence. Until all elements are inserted.

Code:

public class InsertionSort {
 
    public static void main(String a[]){        int[] arr1 = {10,34,2,56,7,67,88,42};        int[] arr2 = doInsertionSort(arr1);        for(int i:arr2){
            System.out.print(i);
            System.out.print(", ");
        }
    }
     
    public static int[] doInsertionSort(int[] input){         
        int temp;        for (int i = 1; i < input.length; i++) {            for(int j = i ; j > 0 ; j--){                if(input[j] < input[j-1]){
                    temp = input[j];                    input[j] = input[j-1];                    input[j-1] = temp;
                }
            }
        }        return input;
    }
}
Copy after login

4. Quick sort

Schematic diagram

What are the sequential sorting methods?

Understanding: Decompose the original problem into several smaller sub-problems but similar structures to the original problem, and solve these sub-problems recursively. problem, and then combine the solutions to these sub-problems into a solution to the original problem.

Code:

public class QuickSort {
     
    private int array[];    private int length; 
    public void sort(int[] inputArr) {         
        if (inputArr == null || inputArr.length == 0) {            return;
        }        this.array = inputArr;
        length = inputArr.length;
        quickSort(0, length - 1);
    } 
    private void quickSort(int lowerIndex, int higherIndex) {         
        int i = lowerIndex;        int j = higherIndex;        // calculate pivot number, I am taking pivot as middle index number
        int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];        // Divide into two arrays
        while (i <= j) {            /**
             * In each iteration, we will identify a number from left side which 
             * is greater then the pivot value, and also we will identify a number 
             * from right side which is less then the pivot value. Once the search 
             * is done, then we exchange both numbers.
             */
            while (array[i] < pivot) {
                i++;
            }            while (array[j] > pivot) {
                j--;
            }            if (i <= j) {
                exchangeNumbers(i, j);                //move index to next position on both sides
                i++;
                j--;
            }
        }        // call quickSort() method recursively
        if (lowerIndex < j)
            quickSort(lowerIndex, j);        if (i < higherIndex)
            quickSort(i, higherIndex);
    } 
    private void exchangeNumbers(int i, int j) {        int temp = array[i];        array[i] = array[j];        array[j] = temp;
    }     
    public static void main(String a[]){
         
        MyQuickSort sorter = new MyQuickSort();        int[] input = {24,2,45,20,56,75,2,56,99,53,12};
        sorter.sort(input);        for(int i:input){
            System.out.print(i);
            System.out.print(" ");
        }
    }
}
Copy after login

5. Merge sort

Principle Figure

What are the sequential sorting methods?

Understanding:Divide the sequence to be sorted into several sub-sequences with a length of 1, and then divide these sequences into two Merge two; obtain several ordered sequence of length 2, and then merge these sequence two by two; obtain several ordered sequence of length 4, and then merge them two by two; until directly merged into one sequence.

Code:

public class MergeSort {
     
    private int[] array;    private int[] tempMergArr;    private int length; 
    public static void main(String a[]){         
        int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
        MyMergeSort mms = new MyMergeSort();
        mms.sort(inputArr);        for(int i:inputArr){
            System.out.print(i);
            System.out.print(" ");
        }
    }     
    public void sort(int inputArr[]) {        this.array = inputArr;        this.length = inputArr.length;        this.tempMergArr = new int[length];
        doMergeSort(0, length - 1);
    } 
    private void doMergeSort(int lowerIndex, int higherIndex) {         
        if (lowerIndex < higherIndex) {            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;            // Below step sorts the left side of the array
            doMergeSort(lowerIndex, middle);            // Below step sorts the right side of the array
            doMergeSort(middle + 1, higherIndex);            // Now merge both sides
            mergeParts(lowerIndex, middle, higherIndex);
        }
    } 
    private void mergeParts(int lowerIndex, int middle, int higherIndex) { 
        for (int i = lowerIndex; i <= higherIndex; i++) {
            tempMergArr[i] = array[i];
        }        int i = lowerIndex;        int j = middle + 1;        int k = lowerIndex;        while (i <= middle && j <= higherIndex) {            if (tempMergArr[i] <= tempMergArr[j]) {                array[k] = tempMergArr[i];
                i++;
            } else {                array[k] = tempMergArr[j];
                j++;
            }
            k++;
        }        while (i <= middle) {            array[k] = tempMergArr[i];
            k++;
            i++;
        }
    }
}
Copy after login

The above is the detailed content of What are the sequential sorting methods?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles