Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement count sorting by Java

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "Java how to achieve count sorting", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Java how to achieve count sorting" bar!

Brief introduction

Count sorting is a space-for-time algorithm, we use an external count array to count the number of occurrences of each element, and finally complete the sorting.

An example of count sorting

Count sorting has certain limitations, because the external length of the count array is the same as the range of elements of the original array, so count sorting is generally only suitable for situations where the range of elements in the array is relatively small.

Let's give an example of the ordering of 0-9 elements: 3pint 4pint 2jre 5jre 6pint 2pint 4pint 9jue 1jue 3jue 5.

Take a look at an animation and see how it is sorted:

The count array stores the number of occurrences of elements from 0 to 9.

We iterate through the original array and give the corresponding count+1 when we encounter the corresponding number.

After all the elements are count, the sorted array is restored based on the values in the count array.

Java implementation of count sorting

Count sorting is simple, and we mainly master the following two big steps:

Iterate through the original array to build the count array.

Rebuilds the sorted array based on the count value in the count array.

Public class CountingSort {public void doCountingSort (int [] array) {int n = array.length; / / stores the sorted array int output [] = new int [n]; / / count array, which is used to store and count the number of occurrences of each element int count [] = new int [10]; for (int item0; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report