Home Java javaTutorial Code example of Java implementation of counting sort (CountingSort)

Code example of Java implementation of counting sort (CountingSort)

Jan 31, 2019 am 11:20 AM

This article brings you code examples about Java implementation of counting sorting (CountingSort). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Counting sorting is a special type of bucket sorting.

When n data are to be sorted, if the range is not large, we can take the maximum value K and disperse the data in K buckets,

Each The data in the buckets are all the same (this saves the time of sorting in the buckets), and then they are taken out in sequence.

Of course, counting and sorting is simple to say, but it is difficult to understand in some places when writing.

For example, we now have 8 numbers: 2, 5, 3, 0, 2, 3, 0, 3. To sort them, we can first get its maximum value of 5, and then determine the range. 0-5,

We apply for a memory space of 0-5 to calculate the number of each number corresponding to each position.

The picture below shows the data of the memory space 0-5. We can see that 0 appears twice, 1 appears 0 times, 2 appears twice, 3 appears three times, and 4 appears. 0 times, 5 appeared once.

At the same time, we can also summarize some rules. For example, we now see the position c[2], 2 appears twice, and there are a total of 2 c[0] c[1] in front of 2. element, so c[2] corresponds to the positions of the two 2s in the original array, which are 2 and 3. We can draw the rule that the position of c[2] = c[0] c[1], and the following c[3] Position = c[2] c[1], we sum them sequentially like this: Then we scan the original array 2, 5, 3, 0, 2, 3, 0, 3. Every time we encounter a number, Substitute this number into the index of the c array to get the real index of the current element after sorting.

My Java implementation is as follows:

package com.structure.sort;
/**
 * @author zhangxingrui
 * @create 2019-01-30 13:45
 **/
public class CountingSort {
    public static void main(String[] args) {
        int[] numbers = {3, 9, 2, 1, 8, 7, 6, 10, 9};
        // 假设数组中存储的都是非负整数
        countingSort(numbers);
        for (int number : numbers) {
            System.out.println(number);
        }
    }
    /**
     * @Author: xingrui
     * @Description: 计数排序
     * @Date: 13:57 2019/1/30
     */
    private static void countingSort(int[] numbers){
        int n = numbers.length;
        int maxNumber = numbers[0];
        for(int i = 1; i < n; ++i){
            if(numbers[i] > maxNumber)
                maxNumber = numbers[i];
        }
        int[] r = new int[n];
        int[] c = new int[maxNumber + 1];
        for(int i = 0; i < n; ++i){
            c[numbers[i]]++;
        }
        for(int i = 1; i <= maxNumber; ++i){
            c[i] = c[i-1] + c[i];
        }
        for (int i = n - 1; i >= 0; --i){
            int index = c[numbers[i]];
            r[index - 1] = numbers[i];
            c[index]--;
        }
        for(int i = 0; i < n; ++i){
            numbers[i] = r[i];
        }
    }
}
Copy after login

The key code:

for (int i = n - 1; i >= 0; --i){
            int index = c[numbers[i]];
            r[index - 1] = numbers[i];
            c[index]--;5         
            }
Copy after login

Retrieve the sorted index from the c array.

The above is the detailed content of Code example of Java implementation of counting sort (CountingSort). 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)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

See all articles