本文介绍了排序算法的 Java 代码实现,所有代码均可通过 菜鸟工具在线编译器 直接运行,因此打算整理一下分享给大家。
简介计算排序假设 n 个输入元素都是 0 到 k 区间内的一个整数,其中 k 为某个整数。
基本原理:
创建一个长度为 k+1 的数组 count[],它的 count[i] 的值对应输入数组中 i 出现的次数。通过遍历一次输入数组并统计每个元素出现次数,最后遍历 count[] 输出。
实例1. Java 代码
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] a = {5, 4, 6, 7, 5, 1, 0, 9, 8, 1};
System.out.println("初始值:");
printArray(a);
countSort(a);
System.out.println("\n排序后:");
printArray(a);
}
public static void countSort(int[] arr) {
int[] count = new int[10];
for (int i = 0; i
关注
打赏