search
HomeJavajavaTutorialHow to implement sorting algorithm using java

Unstable sorting

Selection sorting:
The smallest record obtained after the first round of comparison is exchanged with the position of the first record, and then the smallest record excluding the first record is The records are compared in the second round, and the smallest record obtained is exchanged with the second record
Time complexity: O(n^2)
Space complexity: O(1)

    public static void selectSort(int[] arr){        
    if (arr == null || arr.length == 0)            
    return;        
    int len = arr.length;        
    for (int i = 0; i < len; i++) {            
        int min = arr[i];            
        int index = i;            
        for (int j = i+1; j < len; j++) {                
        if (arr[j] < min) {                    
            min = arr[j];
          index = j;
          }
       }
       arr[index] = arr[i];
       arr[i] = min;
     }
    }

Fast Sorting:
For a given set of records, after each sorting pass, the original sequence is divided into two parts, where all records in the former part are smaller than all records in the latter part, and then the records of the two parts before and after are sequentially Perform quick sort
Time complexity: O(nlogn) Worst: O(n^2)
Space complexity: O(nlogn)

    public int Partition(int[] a,int start,int end){        int std = a[start];
        while (start < end){
             while(start < end && a[end] >= std)                 
             end--;
             a[start] = a[end];
             while(start < end && a[start] <= std)                 
             start++;
             a[end] = a[start];
        }
        a[start] = std;
        return start;
    }
    public void quickSort(int[] a,int start,int end){        
            if(start >= end){
            return;
        }
        int index = Partition(a,start,end);
        quickSort(a,start,index-1);
        quickSort(a,index+1,end);
    }

Heap sort: complete binary tree
Will The binary tree is adjusted to a big top heap, and then the last element of the heap is exchanged with the top element of the heap (that is, the root node of the binary tree). The last element of the heap is the maximum record; then the first n-1 elements are adjusted to Large top heap, and then exchange the top element of the heap with the last element of the current heap to obtain the second largest record. Repeat this process until there is only one element left in the adjusted heap. This element is the minimum record. At this time, you can get a Ordered sequence
Time complexity: O(nlogn)
Space complexity: O(1)

   public void HeapSort(int[] a){        
            for (int i = a.length/2 - 1; i >= 0 ; i--) {
            HeapAdjust(a,i,a.length-1);
        }        
        for (int i = a.length - 1; i >= 0; i--) {
            swap(a,0,i);
            HeapAdjust(a,0,i-1);
        }
    }    
    private void swap(int[] a, int i, int j) {        
            int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }    
    public void HeapAdjust(int[] arr,int s,int len){        
            int tmp = arr[s];        
            for (int i = s * 2 + 1; i < len ; i = i * 2 + 1) {            
                    if (i < len && arr[i] < arr[i+1]){
                i++;
            }            
            if (tmp > arr[i])                
            break;
            arr[s] = arr[i];
            s = i; //s记录被替换的子结点的索引
        }
        arr[s] = tmp;
    }

Stable sorting

Direct insertion sorting:
The first one The records can be regarded as forming an ordered sequence, and the remaining records are called unordered sequences. Then starting from the second record, insert the currently processed record into the previous ordered sequence in order according to the size of the record until the last record is inserted into the ordered sequence
Time complexity: O(n^2)
Space complexity: O(1)

    public static void insertSort(int[] arr){        
            if (arr == null || arr.length == 0)            
            return;        
            int len = arr.length;        
            for (int i = 1; i < len; i++) {            
            int curr = arr[i];            
            int j = i;            
            if (arr[j-1] > curr){                
                while (j > 0 && arr[j-1]> curr){
                arr[j] = arr[j-1];
                j--;
                }
            }
          arr[j] = curr;
        }
    }

Bubble sorting:
Starting from the first record, two adjacent records are compared in sequence. When the previous record is larger than the following record, the positions are swapped. After a round of comparison and transposition, the largest record among the n records will be located at the nth record. bit, and then perform a second round of comparison on the previous n-1 records, and repeat the process until only one record is compared
Time complexity: O(n^2)
Space complexity: O(1)

    public void bubbleSort(int[] arr){        
            boolean flag = true;        
            for (int i = 0; i < arr.length && flag; i++) {
            flag = false;            
            for (int j = 0; j < arr.length - i - 1; j++) {                
                    if (arr[j] > arr[j+1]){
                flag = true;
                swap(arr,j,j+1);
                }
            }
        }
    }    
    private void swap(int[] arr, int j, int i) {        
            int tmp = arr[j];
        arr[j] = arr[i];
        arr[i] = tmp;
    }

Merge sort: recursion, and: merge separate data in an orderly manner
Merge every two adjacent subsequences of length 1 to obtain n/2 ordered subsequences of length 2 or 1, then merge the two, and repeat this process until an ordered sequence is obtained
Time complexity: O(nlogn)
Space complexity: O(n)

   public static void mergeSort(int[] arr,int begin,int end){        
              int mid = (begin+end)/2;        
              if (begin < end){
            mergeSort(arr,begin,mid);
            mergeSort(arr,mid+1,end);
            Merge(arr,begin,end,mid);
        }
    }    
    public static void Merge(int[] arr,int begin,int end,int mid){        
            int[] temp = new int[end-begin+1];        
            int i = begin;        
            int j = mid+1;        
            int k=0;        
            while (i <= mid && j <= end){            
            if (arr[i] < arr[j]){
                temp[k++] = arr[i++];
            }else{
                temp[k++] = arr[j++];
            }
        }        
        while (i <= mid){
            temp[k++] = arr[i++];
        }        
        while (j <= end){
            temp[k++] = arr[j++];
        }        
        for (int m = 0;m < temp.length;m++){
            arr[m+begin] = temp[m];
        }
    }

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

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
使用Python实现XML数据的筛选和排序使用Python实现XML数据的筛选和排序Aug 07, 2023 pm 04:17 PM

使用Python实现XML数据的筛选和排序引言:XML是一种常用的数据交换格式,它以标签和属性的形式存储数据。在处理XML数据时,我们经常需要对数据进行筛选和排序。Python提供了许多有用的工具和库来处理XML数据,本文将介绍如何使用Python实现XML数据的筛选和排序。读取XML文件在开始之前,我们需要先读取XML文件。Python有许多XML处理库,

C++程序:按字母顺序重新排列单词的位置C++程序:按字母顺序重新排列单词的位置Sep 01, 2023 pm 11:37 PM

在这个问题中,一个字符串被作为输入,我们必须按字典顺序对字符串中出现的单词进行排序。为此,我们为字符串中的每个单词(之间用空格区分)分配一个从1开始的索引,并以排序索引的形式获得输出。String={“Hello”,“World”}“Hello”=1“World”=2由于输入字符串中的单词已按字典顺序排列,因此输出将打印为“12”。让我们看看一些输入/结果场景-假设输入字符串中的所有单词都相同,让我们看看结果-Input:{“hello”,“hello”,“hello”}Result:3获得的结

如何优化Java集合排序性能如何优化Java集合排序性能Jun 30, 2023 am 10:43 AM

Java是一种功能强大的编程语言,广泛应用于各类软件开发中。在Java开发中,经常会涉及到对集合进行排序的场景。然而,如果不对集合排序进行性能优化,可能会导致程序的执行效率下降。本文将探讨如何优化Java集合排序的性能。一、选择合适的集合类在Java中,有多种集合类可以用来进行排序,如ArrayList、LinkedList、TreeSet等。不同的集合类在

Java开发中如何优化集合排序去重性能Java开发中如何优化集合排序去重性能Jul 02, 2023 am 11:25 AM

Java开发中,集合排序和去重是常见的需求。然而,在处理大数据集合时,性能往往会成为一个问题。本文将介绍一些优化技巧,帮助提升集合排序和去重的性能。一、使用合适的数据结构在Java中,最常用的数据结构是ArrayList和HashSet。ArrayList适用于需要保持元素顺序的情况,而HashSet则适用于需要去重的情况。在排序和去重的场景中,我们可以使用

如何利用vue和Element-plus实现数据的分组和排序如何利用vue和Element-plus实现数据的分组和排序Jul 18, 2023 am 10:39 AM

如何利用Vue和ElementPlus实现数据的分组和排序Vue是一种流行的JavaScript框架,它可以帮助我们构建前端应用程序。ElementPlus是基于Vue的桌面端组件库,它提供了丰富的UI组件,使我们能够轻松地构建出漂亮且用户友好的界面。在本文中,我们将探讨如何利用Vue和ElementPlus来实现数据的分组和排序。首先,我们需要准备一

Java实现的常见排序算法详解Java实现的常见排序算法详解Jun 18, 2023 am 10:48 AM

排序算法是计算机科学中的一个重要概念,是许多应用程序的核心部分。在日常生活和工作中,我们经常需要对数据进行排序,例如排列名单、对数值进行排序等。Java作为一种广泛使用的编程语言,提供了许多内置的排序算法。本文将详细介绍Java中实现的常见排序算法。1.冒泡排序(BubbleSort)冒泡排序是最简单但最慢的排序算法之一。它遍历整个数组,比较相邻的元素并一

PHP usort() 函数使用指南:排序数组PHP usort() 函数使用指南:排序数组Jun 27, 2023 pm 02:27 PM

PHPusort()函数使用指南:排序数组在PHP编程中,我们经常需要对数组进行排序。PHP提供了很多函数用于数组的排序,其中usort()函数可以灵活的对数组进行自定义排序。本文将介绍usort()函数的使用方法和注意事项,并通过实例演示如何使用usort()函数对数组进行排序。一、usort()函数简介PHPusort()函数

如何在Java 14中使用Records类来实现自动比较和排序如何在Java 14中使用Records类来实现自动比较和排序Jul 30, 2023 pm 01:06 PM

如何在Java14中使用Records类来实现自动比较和排序Java14引入了一种新的类称为Records类,它为我们提供了一种简洁而强大的方式来定义不可变的数据类。Records类具有自动为每个字段生成getter方法、equals()方法和hashCode()方法的特性,这使得比较和排序非常方便。在这篇文章中,我们将通过示例代码来演示如何在Java

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)