Detailed Java sorting algorithm commonly used (10 kinds)

The sorting algorithms commonly used in Java are as follows:

  1. Bubble Sort
  2. Selection Sort
  3. Insertion Sort
  4. Shell sort (Shell Sort)
  5. Merge Sort
  6. Quick sort (Quick Sort)
  7. Heap Sort
  8. Counting Sort
  9. Bucket Sort
  10. Radix Sort (Radix Sort)

These sorting algorithms have their own advantages and disadvantages, and the appropriate algorithm should be selected according to the specific situation.

1. Bubble Sort

Bubble sort is a simple sorting algorithm that repeatedly traverses the array to be sorted, comparing two elements at a time, and swapping positions if they are in the wrong order. This process continues towards the end of the sequence until the entire sequence is sorted.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Bubble {
    
    
    public static void bubbleSort(int[] arr) {
    
    
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
    
    
            for (int j = 0; j < n - i - 1; j++) {
    
    
                if (arr[j] > arr[j + 1]) {
    
    
                    // 交换arr[j+1]和arr[j]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8};
        Bubble.bubbleSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the bubbleSort function takes an array of integers as input and sorts it using the bubble sort algorithm. The outer loop runs n - 1 times, where n is the length of the array, and the inner loop runs n - i - 1 times, where i is the current iteration number of the outer loop. This is because after each iteration of the outer loop, the largest element is definitely at the end of the array, so we don't need to compare it again.

In the inner loop we compare adjacent elements and swap them if they are not in the correct order. This way, the largest element "bubbles up" to the end of the array. After each pass through the array, the largest element is in its final position, so we can reduce the size of the inner loop by 1.

The time complexity of bubble sort is O(n^2), which makes it inefficient for large lists and practical applications. However, due to its simplicity, it is a good algorithm for teaching sorting to beginners.

2. Selection Sort

Selection sort is a simple sorting algorithm. Its basic idea is to select the smallest (or largest) element from the elements to be sorted each time, and store it at the beginning of the sequence until all the elements to be sorted are exhausted.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Selection {
    
    
    public static void selectionSort(int[] arr) {
    
    
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
    
    
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
    
    
                if (arr[j] < arr[minIndex]) {
    
    
                    minIndex = j;
                }
            }
            // 交换arr[i]和arr[minIndex]
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8};
        Selection.selectionSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the selectionSort function takes an array of integers as input and sorts it using the selection sort algorithm. The outer loop runs n - 1 times, where n is the length of the array. In the inner loop, we find the smallest element in the unsorted part and store its index in the minIndex variable. Then we swap the smallest element with the end of the sorted part. After each outer loop iteration, the length of the sorted part is increased by 1 and the length of the unsorted part is decreased by 1.

The time complexity of selection sort is O(n^2), which makes it inefficient for large lists and practical applications. However, due to its simplicity, it is a good algorithm for teaching sorting to beginners.

3. Insertion Sort

Insertion sorting is a simple sorting algorithm. Its basic idea is to insert a record into an already sorted ordered list to obtain a new ordered list with the number of records increased by 1.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Insertion {
    
    
    public static void insertionSort(int[] arr) {
    
    
        int n = arr.length;
        // 外部循环从第二个元素开始,因为我们将第一个元素视为已排序部分
        for (int i = 1; i < n; i++) {
    
    
            int key = arr[i];
            int j = i - 1;
            // 将当前值key和前面的值进行比较,如果前面的值>key 则将值往后移1位
            while (j >= 0 && arr[j] > key) {
    
    
                arr[j + 1] = arr[j];
                j--;
            }
            // 在不小当前值key的位置,插入当前值key
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8};
        Insertion.insertionSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the insertionSort function takes an array of integers as input and sorts it using the insertion sort algorithm. The outer loop starts with the second element, since we consider the first element as the sorted part. In the inner loop, we compare the element to be inserted with the element of the sorted part, and if the element to be inserted is smaller than the element of the sorted part, we shift the element of the sorted part one bit to the right to make room for the element to be inserted. After the inner loop finishes, we insert the element to be inserted in the correct position. After each outer loop iteration, we can ensure that the first i elements have been sorted.

Insertion sort has a time complexity of O(n^2), which makes it inefficient for large lists and practical applications. However, insertion sort is very simple to implement, and it performs very well on small lists.

4. Shell Sort

Hill sorting is an improved insertion sorting algorithm. Its basic idea is to group the array to be sorted according to a certain interval, sort each group using the insertion sorting algorithm, then narrow the interval, and then sort the grouping until the interval is 1.

The method of gradually reducing the size of the interval helps to improve the efficiency of the sorting process, which can reduce the number of comparisons and exchanges. This is a key feature of the Hill sort algorithm.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Shell {
    
    
    public static void shellSort(int[] arr) {
    
    
        int n = arr.length;
        // 初始化间隔(gap)的值,它决定了每次迭代中子数组的大小
        // 从数组长度的一半开始作为初始间隔值,gap就是分割的子数组数量
        for (int gap = n / 2; gap > 0; gap /= 2) {
    
    
            // 循环从间隔值开始,遍历数组直到数组的末尾;代表循环所有的子数组
            for (int i = gap; i < n; i++) {
    
    
                int temp = arr[i];
                int j = i;
                // 将当前元素 arr[j] 的值替换为前一个元素 arr[j - gap] 的值。
                // 通过这个操作,将较大的元素向后移动,为当前元素腾出位置
                while (j >= gap && arr[j - gap] > temp) {
    
    
                    arr[j] = arr[j - gap];
                    j -= gap;
                }
                arr[j] = temp;
            }
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8};
        Shell.shellSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the shellSort function takes an array of integers as input and sorts it using the Shell sort algorithm. The outer loop uses an interval variable gap with an initial value of half the length of the array, and divides gap by 2 each time through the loop until gap is 1. The inner loop starts at the gapth element, compares the element to be inserted with the elements of the sorted part, and if the element to be inserted is smaller than the element of the sorted part, moves the elements of the sorted part to the right by gap positions to make room for the element to be inserted. After the inner loop finishes, we insert the element to be inserted in the correct position. After each iteration of the outer loop, we can ensure that the first gap elements of the array are sorted.

Hill sort has a time complexity of O(n^2), but in practice it performs much better than insertion sort, especially on large lists. The performance of Hill sorting depends on the choice of spacer sequence, but there is no optimal spacer sequence yet.

5. Merge Sort

Merge sort is a divide-and-conquer sorting algorithm. Its basic idea is to divide the array to be sorted into several subsequences, each subsequence is ordered, and then merge the subsequences into an ordered array.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Merge {
    
    
    public static void mergeSort(int[] arr, int left, int right) {
    
    
        if (left < right) {
    
    
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right) {
    
    
        // 子数组 L 的大小
        int n1 = mid - left + 1;
        // 右子数组 R 的大小
        int n2 = right - mid;
        // 创建两个临时数组 L 和 R ,分别用来存储左子数组和右子数组的元素
        int[] L = new int[n1];
        int[] R = new int[n2];
        // 使用 for 循环将原始数组 arr 中的元素复制到临时数组 L 和 R 中,分别从 left 和 mid + 1 开始
        for (int i = 0; i < n1; i++) {
    
    
            L[i] = arr[left + i];
        }
        for (int j = 0; j < n2; j++) {
    
    
            R[j] = arr[mid + 1 + j];
        }
        // 初始化三个变量 i、j和k,分别指向数组 L 、R 和原始数组 arr 的起始位置
        int i = 0, j = 0, k = left;
        // 使用 while 循环,比较 L 和 R 的元素,并将较小的元素放回原始数组 arr 中
        while (i < n1 && j < n2) {
    
    
            if (L[i] <= R[j]) {
    
    
                arr[k] = L[i];
                i++;
            } else {
    
    
                arr[k] = R[j];
                j++;
            }
            k++;
        }
        // 当 L 或 R 中的元素用完时,将剩余的元素依次放回原始数组 arr 中
        while (i < n1) {
    
    
            arr[k] = L[i];
            i++;
            k++;
        }
        while (j < n2) {
    
    
            arr[k] = R[j];
            j++;
            k++;
        }
        // merge 方法执行完毕后,两个子数组范围内的元素已经按照从小到大的顺序合并到了原始数组 arr 中
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8};
        Merge.mergeSort(arr, 0, arr.length - 1);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the mergeSort function accepts an integer array, a left index and a right index as input and uses the merge sort algorithm to sort the array elements within the specified range. This function uses recursion to split the array into two sub-arrays, then sorts them, and finally merges them into one sorted array. The merge function is used to merge two sorted arrays into one sorted array. It creates two temporary arrays L and R, stores the elements of the left sub-array in L and the right sub-array in R, then merges them into one sorted array and stores it in the original array.

The time complexity of merge sort is O(nlogn), and its performance is much better than bubble sort and insertion sort, especially on large lists.

6. Quick Sort

Quick sort is a sorting algorithm with a divide-and-conquer idea. Its basic idea is to separate the records to be sorted into two independent parts through one-pass sorting. The keywords of one part of the records are smaller than the keywords of the other part of the records, and then continue to sort the two parts of the records respectively, so as to achieve the purpose of ordering the entire sequence.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Quick {
    
    
    // 接收一个数组 arr,一个低索引 low ,和一个高索引 high 作为参数
    public static void quickSort(int[] arr, int low, int high) {
    
    
        // 检查 low 是否小于 high。如果不是,则意味着数组只有一个元素或为空,因此不需要排序
        if (low < high) {
    
    
            int pivot = partition(arr, low, high);
            quickSort(arr, low, pivot - 1);
            quickSort(arr, pivot + 1, high);
        }
    }

    private static int partition(int[] arr, int low, int high) {
    
    
        // 将最后一个元素作为枢轴元素( arr[high] )
        int pivot = arr[high];
        // 将 i 初始化为 low - 1,用于跟踪较小元素的索引
        int i = low - 1;
        for (int j = low; j < high; j++) {
    
    
            if (arr[j] < pivot) {
    
    
                // 如果当前元素 arr[j] 小于枢轴元素,则增加 i 并交换 arr[i] 和 arr[j]
                // 较小元素索引+1
                i++;
                // 将当前元素 arr[j] 放在较小元素索引位置
                swap(arr, i, j);
            }
            // 其他情况,则较小元素索引没有增加,说明当前元素应该放在右边
        }
        // 将枢轴元素( arr[high] )与索引 i + 1 处的元素交换。
        // 确保枢轴元素左边是较小元素,右边是较大元素
        swap(arr, i + 1, high);
        // 将 i + 1 作为枢轴索引返回
        return i + 1;
    }

    private static void swap(int[] arr, int i, int j) {
    
    
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 6, 1, 3};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8};
        Quick.quickSort(arr, 0, arr.length - 1);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the quickSort function takes an integer array, a low index and a high index as input and uses the quick sort algorithm to sort the array elements within the specified range. This function uses recursion to split the array into two sub-arrays, then sorts them, and finally merges them into one sorted array. The partition function is used to divide an array into two subarrays. It selects the last element in the array as the pivot element, then places elements smaller than the pivot element on the left and elements greater than the pivot element on the right, and returns the index of the pivot element. The swap function is used to swap two elements in an array.

The time complexity of quicksort is O(nlogn), and its performance is much better than bubble sort and insertion sort, especially on large lists.

7. Heap Sort

Heap sorting is a tree selection sorting algorithm. Its basic idea is to build the array to be sorted into a large root heap (or small root heap), then exchange the position of the top element and the bottom element of the heap, and then rebuild the remaining elements into a heap, and repeat the operation of exchanging and reconstructing the heap until the entire array is in order.

Heap sort is a sorting algorithm based on heap data structure, and its time complexity is O(nlogn).

heap concept

The set K = {k0, k1, k2, ..., kn-1} stores all its elements in a one-dimensional array in the order of a complete binary tree, and satisfies: Ki <= K2i+1 (left node) and Ki<=K2i+2 (right node), then it is called a small heap (or a large heap). The heap with the largest root node is called the largest heap or large root heap, and the heap with the smallest root node is called the smallest heap or small root heap. Complete binary tree (except for the last layer, the upper nodes are not empty, and the last layer nodes are arranged from left to right)

The nature of the heap

1. The value of a node in the heap is always not greater than or not less than the value of its parent node;
2. The heap is always a complete binary tree.

public class Heap {
    
    

    public static void heapSort(int[] arr) {
    
    
        int n = arr.length;
        // 构建大根堆
        // 这段代码是构建大根堆的过程,它的循环次数为n/2-1次,是因为在完全二叉树中,叶子节点不需要进行堆化操作,
        // 所以只需要对非叶子节点进行堆化,而非叶子节点的数量为n/2-1个。因此,只需要循环n/2-1次即可完成大根堆的构建。
        // 非叶子节点在一维数组中就是前面 n/2-1
        for (int i = n / 2 - 1; i >= 0; i--) {
    
    
            heapify(arr, n, i);
        }
        // 依次取出堆顶元素,并将余下元素继续堆化,得到有序序列
        for (int i = n - 1; i >= 0; i--) {
    
    
            swap(arr, 0, i);
            heapify(arr, i, 0);
        }
    }

    private static void heapify(int[] arr, int heapSize, int i) {
    
    
        int largest = i; // 初始化最大值为根节点
        int left = 2 * i + 1;
        int right = 2 * i + 2;
        // 找到左右子节点中的最大值
        if (left < heapSize && arr[left] > arr[largest]) {
    
    
            largest = left;
        }
        if (right < heapSize && arr[right] > arr[largest]) {
    
    
            largest = right;
        }
        // 如果最大值不是根节点,则交换根节点与最大值节点,并递归地对最大值节点进行堆化
        if (largest != i) {
    
    
            swap(arr, i, largest);
            heapify(arr, heapSize, largest);
        }
    }

    private static void swap(int[] arr, int i, int j) {
    
    
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 12, 35, 57, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8, 12, 35, 57};
        Heap.heapSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the heapSort function takes an array of integers as input and sorts the array using the heapsort algorithm. This function first builds a large root heap, and then takes out the top elements of the heap in turn to obtain an ordered sequence. The heapify function is used to heap a node. It takes three parameters: the array to be heapified, the size of the array, and the index of the node to be heapified. This function first finds the maximum value among the left and right child nodes. If the maximum value is not the root node, then exchange the root node and the maximum value node, and recursively heap the maximum value node. The swap function is used to swap two elements in an array.

8. Counting Sort

Counting sorting is a non-comparative sorting algorithm. Its basic idea is to count the number of occurrences of each element in the array, and then put the elements into an ordered array in turn according to the number of occurrences of the element.

The time complexity of counting sort is O(n+k), where k is the maximum number of elements to be sorted.

import org.junit.jupiter.api.Assertions;
import java.util.Arrays;

public class Counting {
    
    
    public static void countingSort(int[] arr) {
    
    
        int n = arr.length;
        // 取出数组中最大值
        int max = getMax(arr);
        int[] count = new int[max + 1];
        // 统计每个元素出现的次数
        for (int i = 0; i < n; i++) {
    
    
            count[arr[i]]++;
        }
        // 计算每个元素在有序序列中的位置
        for (int i = 1; i <= max; i++) {
    
    
            // 因为count包含了每个数据出现的次数,所以从小到大,逐个往前加得到就是原数组中每个元素在有序序列中应有的位置
            count[i] += count[i - 1];
        }
        // 输出有序序列
        int[] sortedArr = new int[n];
        for (int i = n - 1; i >= 0; i--) {
    
    
            sortedArr[count[arr[i]] - 1] = arr[i];
            count[arr[i]]--;
        }
        // 将有序序列复制回原数组
        System.arraycopy(sortedArr, 0, arr, 0, n);
    }

    private static int getMax(int[] arr) {
    
    
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
    
    
            if (arr[i] > max) {
    
    
                max = arr[i];
            }
        }
        return max;
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 1, 6, 12};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8, 12};
        Counting.countingSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

9. Bucket Sort

Bucket sorting is a non-comparative sorting algorithm. Its basic idea is to divide the array to be sorted into a limited number of buckets, then sort each bucket, and finally take out the elements in all buckets in turn to form an ordered array.

The time complexity of bucket sorting is O(n), where n is the number of elements to be sorted.

import org.junit.jupiter.api.Assertions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Bucket {
    
    
    /**
     * 桶排序
     * @param arr 待排序数组
     * @param bucketSize 桶大小,数据不宜过大,桶越大,后续对桶内数据排序越耗时
     */
    public static void bucketSort(int[] arr, int bucketSize) {
    
    
        if (arr.length == 0) {
    
    
            return;
        }
        // 循环数组,先找到最小值和最大值
        int minValue = arr[0];
        int maxValue = arr[0];
        for (int i = 1; i < arr.length; i++) {
    
    
            if (arr[i] < minValue) {
    
    
                minValue = arr[i];
            } else if (arr[i] > maxValue) {
    
    
                maxValue = arr[i];
            }
        }
        // 根据桶的大小,计算桶个数,并初始化桶
        int bucketCount = (maxValue - minValue) / bucketSize + 1;
        List<List<Integer>> buckets = new ArrayList<>(bucketCount);
        for (int i = 0; i < bucketCount; i++) {
    
    
            buckets.add(new ArrayList<>());
        }
        for (int i = 0; i < arr.length; i++) {
    
    
            int bucketIndex = (arr[i] - minValue) / bucketSize;
            buckets.get(bucketIndex).add(arr[i]);
        }
        int currentIndex = 0;
        for (int i = 0; i < bucketCount; i++) {
    
    
            List<Integer> bucket = buckets.get(i);
            // 对桶内数据进行排序
            Collections.sort(bucket);
            // 将数据逐个从桶内取出,并存入数组
            for (int j = 0; j < bucket.size(); j++) {
    
    
                arr[currentIndex++] = bucket.get(j);
            }
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 12, 35, 57, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8, 12, 35, 57};
        Bucket.bucketSort(arr, 20);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the bucketSort function takes an array of integers and the size of the bucket as input and sorts the array using the bucket sort algorithm. The function first finds the minimum and maximum values ​​in the input array and counts the number of buckets. Then, the function creates a list of buckets whose size is the number of buckets to store the elements in each bucket. Next, the function iterates through the input array in turn, placing each element into the corresponding bucket. Then, the function sorts the elements in each bucket and merges the sorted elements in order to obtain an ordered sequence.

10. Radix Sort

Radix sorting is a non-comparative sorting algorithm. Its basic idea is to divide the array to be sorted according to the number of digits (units, tens, and hundreds), and then sort the numbers in each digit in turn to finally obtain an ordered array.

The time complexity of radix sorting is O(d(n+k)), where d is the number of digits of the largest element, n is the number of elements to be sorted, and k is the number of buckets.

import org.junit.jupiter.api.Assertions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Radix {
    
    
    public static void radixSort(int[] arr) {
    
    
        if (arr.length == 0) {
    
    
            return;
        }
        int maxNum = arr[0];
        for (int i = 1; i < arr.length; i++) {
    
    
            if (arr[i] > maxNum) {
    
    
                maxNum = arr[i];
            }
        }
        int maxDigit = 0;
        while (maxNum != 0) {
    
    
            maxNum /= 10;
            maxDigit++;
        }
        List<List<Integer>> buckets = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
    
    
            buckets.add(new ArrayList<>());
        }
        int mod = 10; // 初始10,用于数据个位数取模
        int div = 1; // 桶序号除数
        // 按位数循环数组,如果数据中有十位数的数据,循环2次,百位数循环3次
        for (int i = 0; i < maxDigit; i++, mod *= 10, div *= 10) {
    
    
            // 循环数组,将数据分别存入桶中
            for (int j = 0; j < arr.length; j++) {
    
    
                // 计算当前位数的桶序号
                int bucketIndex = (arr[j] % mod) / div;
                buckets.get(bucketIndex).add(arr[j]);
            }
            // 循环桶列表,将当前位数已排序的数据放入数组中
            int currentIndex = 0;
            for (int j = 0; j < 10; j++) {
    
    
                List<Integer> bucket = buckets.get(j);
                for (int k = 0; k < bucket.size(); k++) {
    
    
                    arr[currentIndex++] = bucket.get(k);
                }
                bucket.clear();
            }
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = {
    
    5, 2, 8, 3, 12, 35, 57, 1, 6};
        int[] expectedArr = {
    
    1, 2, 3, 5, 6, 8, 12, 35, 57};
        Radix.radixSort(arr);
        System.out.println("arr = " + Arrays.toString(arr));
        Assertions.assertArrayEquals(expectedArr, arr);
    }
}

In the above code, the radixSort function takes an array of integers as input and sorts the array using the radix sort algorithm. The function first finds the maximum value in the input array and calculates the number of digits in the maximum value. The function then creates a bucket list of size 10 to store the elements in each bucket. Next, the function iterates through each bit of the input array in turn, placing each element in its corresponding bucket. Then, the function combines the elements in each bucket in order to obtain an ordered sequence.

Guess you like

Origin blog.csdn.net/wlddhj/article/details/131482951