Java's eight sorting algorithms
one: define
Sorting: sort a sequence of objects according to a certain keyword
Two: Bubble sort
Bubble sort is the first sorting algorithm touched
Basic idea:
Bubble Sort (Bubble Sort) is a simple sort. It has repeatedly visited the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until there is no need to exchange, that is to say, the sequence has been sorted.
Algorithm Description
1. Compare adjacent elements, if the first one is greater than the second, swap them two
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step is done, the last element will be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.
Code
public static void BubbleSort(int[] numbers){
//外层循环控制比较次数
for (int i=0;i<numbers.length-1;i++){
//内层循环控制到达位置
for (int j=0;j<numbers.length-1-i;j++){
//比较前面的元素比后面元素大交换,同理也可以比较小
if (numbers[j]>numbers[j+1]){
int temp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
}
}
}
}
//调用
int[] n={60,38,5,14,7,23,89,77,88,4,35,45,67,99,87};
System.out.println(Arrays.toString(n));
BubbleSort(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
Optimization of bubble sort
In this case, it may have been sorted in the last few passes, and the sorting operation is still continuing, so we can add a mark to the exchange place. If there is no exchange element in the sorting pass, it means that this set of data is already in order. Go on.
//减少一些可能循环的次数
public static void BubbleSort(int[] numbers){
//外层循环控制比较次数
for (int i=0;i<numbers.length-1;i++){
int flag=0;//默认标记为0
//内层循环控制到达位置
for (int j=0;j<numbers.length-1-i;j++){
//比较前面的元素比后面元素大交换,同理也可以比较小
if (numbers[j]>numbers[j+1]){
int temp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
flag=1;//如果还有交换,标记为1
}
}
if (flag==0){//如果没有交换过的元素,则已经有序了
return;
}
}
}
Complexity analysis
Bubble sort is the easiest sort to implement. In the worst case, it needs to be exchanged every time. It needs to be traversed and exchanged nearly n²/2 times, and the time complexity is O(n²). The best case is the inner loop traversal once After finding that the sorting is correct, the time complexity is O(n) to exit the loop. On average, the time complexity is O(n²). Since only the cached temp variable in the bubble sort requires memory space, the space is complicated The degree is a constant O(1).
3: Quick sort
Quick sort is a sorting algorithm developed by Tony Hall. On average, it takes Ο(nlogn) comparisons to sort n items. In the worst case, Ο(n2) comparisons are required, but this situation is not common. In fact, quicksort is usually significantly faster than other Ο(nlogn) algorithms, because its inner loop can be implemented efficiently on most architectures
Basic idea
The basic idea of quick sorting: digging holes and filling numbers + divide and conquer method.
Quick sort uses a divide and conquer (Divide and conquer) strategy to divide a list into two sub-lists.
Quick sort is a typical application of divide and conquer in sorting algorithms. Essentially, quick sort should be regarded as a recursive divide-and-conquer method based on bubble sort.
The name of Quick Sort is simple and rude, because once you hear the name, you know its meaning, which is fast and efficient! It is one of the fastest sorting algorithms for processing big data. Although the time complexity of Worst Case has reached O(n²), it is excellent. In most cases, it performs better than the sorting algorithm with an average time complexity of O(n logn).
Algorithm Description
Quicksort uses a divide-and-conquer strategy to divide a sequence (list) into two sub-lists (sub-lists). The steps are:
1. Pick an element from the sequence and call it "benchmark"
2. Re-order the sequence, all elements smaller than the benchmark are placed in front of the benchmark, and all elements larger than the benchmark are placed behind the benchmark. The same number can go to either side). After this partition is over, the benchmark is in the middle of the sequence. This is called a partition operation.
3. Recursively sort the sub-sequences of elements smaller than the reference value and the sub-sequences of elements larger than the reference value.
When the recursion reaches the bottom, the size of the sequence is zero or one, that is, it has been sorted. This algorithm will definitely end, because in each iteration, it will put at least one element to its last position.
Code
public static void QuickSort(int[] a, int low, int high) {
//这里的low 和hight 传递的是数组的起始位置0,和数组的结束位置length-1
//已经排完
if (low >= high) {
return;
}
int left = low;//起始位置0,这位置是改变的
int right = high;//结束位置length-1,这位置是改变的
//保存基准值
//这里是把起始位置的数,设置为基准数,如60
int pivot = a[left];
while (left < right) {
//从后向前找到比基准小的元素
while (left < right && a[right] >= pivot)
right--;
a[left] = a[right];
//从前往后找到比基准大的元素
while (left < right && a[left] <= pivot)
left++;
a[right] = a[left];
}
// 放置基准值,准备分治递归快排
a[left] = pivot;
QuickSort(a, low, left - 1);
QuickSort(a, left + 1, high);
}
//使用
int[] n={60,38,5,14,7,23,89,77,88,4,35,45,67,99,87};
System.out.println(Arrays.toString(n));
QuickSort(n,0,n.length-1);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
The above is the recursive version of quick sort: divide and conquer by inserting the benchmark into the appropriate position, and recursively continue to quickly sort the two divisions after the divide and conquer. So how to realize the non-recursive version of fast sorting?
Knowledge expansion
Because recursion is the stack , so in our non-recursive implementation process, we can use the stack to save intermediate variables to achieve non-recursion. Here the intermediate variable is the head and tail pointer that is divided into the left and right parts after dividing the interval by the Praitation function. You only need to save the head and tail pointers of these two parts.
public static void QuickSortByStack(int[] a) {
Stack<Integer> stack = new Stack<Integer>();//定义栈
//初始状态的左右指针入栈
stack.push(0);
stack.push(a.length - 1);
while (!stack.isEmpty()) {
//出栈进行划分
int high = stack.pop();
int low = stack.pop();
int pivotIndex = partition(a, low, high);
//保存中间变量
if (pivotIndex > low) {
stack.push(low);
stack.push(pivotIndex - 1);
}
if (pivotIndex < high && pivotIndex >= 0) {
stack.push(pivotIndex + 1);
stack.push(high);
}
}
}
private static int partition(int[] a, int low, int high) {
if (low >= high) return -1;
int left = low;
int right = high;
//保存基准的值
int pivot = a[left];//最左边的数值为基准
while (left < right) {
//从后向前找到比基准小的元素,插入到基准位置中
while (left < right && a[right] >= pivot) {
right--;
}
a[left] = a[right];
//从前往后找到比基准大的元素
while (left < right && a[left] <= pivot) {
left++;
}
a[right] = a[left];
}
//放置基准值,准备分治递归快排
a[left] = pivot;
return left;
}
//使用
int[] n={60,38,5,14,7,23,89,77,88,4,35,45,67,99,87};
System.out.println(Arrays.toString(n));
QuickSortByStack(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
above two bubble sort and quick sort belong to exchange sort
4: Direct insertion sort
Basic idea
Usually, people organize the bridge cards one by one, inserting each card into the proper position of the other cards that are already in order. In the computer implementation, in order to make room for the inserted element, we need to move all the remaining elements one place to the right before inserting.
Algorithm Description
Generally speaking, insertion sort is implemented on the array using in-place. The specific algorithm is described as follows:
1. Starting from the first element, the element can be considered to have been sorted
2. Take out the next element and scan from back to front in the sequence of sorted elements (comparison from the second element with the sorted before)
3. If the element (sorted) is larger than the new element, move the element to the next position
4. Repeat step 3 until you find the position where the sorted element is less than or equal to the new element
5. After inserting the new element into the position
6. Repeat steps 2~5
Code
public static void InsertSort(int[] numbers){
for (int i=0;i<numbers.length-1;i++){
//外层循环控制比较次数
for (int j=i+1;j>0;j--){
//从第二个元素开始比较
if (numbers[j]<numbers[j-1]) {
//例如第一次,如果第2个元素小于默认排好的第一个元素
int temp=numbers[j];//第二个元素赋值给临时变量
numbers[j]=numbers[j-1];//第一个元素赋值给第二元素
numbers[j-1]=temp;//临时变量赋值给第一个元素
}
}
}
}
A variant of insertion sort, binary insertion sort
public static void binaryInsertSort(int[] numbers) {
if (numbers != null && numbers.length > 1) {
for (int i = 1; i < numbers.length; i++) {
int left = 0;
int right = i-1;
int mid;
int temp = numbers[i];
if(temp < numbers[right]){ // 当前值小于有序序列的最大值时,开始查找插入位置
while(left <= right){
mid = (left + right)/2;
if(numbers[mid] < temp){
left = mid + 1; // 缩小插入区间
}else if(numbers[mid] > temp){
right = mid - 1; // 缩小插入区间
}else{ // 待插入值与有序序列中的target[mid]相等,保证稳定性的处理
left = left + 1;
}
}
// left及其后面的数据顺序向后移动,并在left位置插入
for (int j = i; j > left; j--) {
numbers[j] = numbers[j-1];
}
numbers[left] = temp;
}
}
}
}
//使用
int[] n={60,38,5,14,7,23,89,77,88,4,35,45,67,99,87};
System.out.println(Arrays.toString(n));
binaryInsertSort(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
five: Hill sort
Hill sorting, also known as decreasing incremental sorting algorithm, is a more efficient and improved version of insertion sorting. Hill sorting is an unstable sorting algorithm.
Hill sorting proposes an improved method based on the following two properties of insertion sorting:
Insertion sorting is highly efficient when operating on data that has almost been sorted, that is, it can achieve the efficiency of linear sorting
But insertion sort is generally inefficient, because insertion sort can only move the data by one at a time
Hill sorting first divides the entire sequence of records to be sorted into several sub-sequences to perform direct insertion sorting respectively. When the records in the entire sequence are "basically ordered", then the entire record sequence is directly inserted and sorted.
Basic idea
The array to be sorted is grouped according to the step gap, and then the elements of each group are sorted by the method of direct insertion sort; each time the gap is reduced by half, and the above operation is repeated; when gap=1, use direct insertion to complete Sort.
It can be seen that the choice of step size is an important part of Hill sorting. Any step sequence can work as long as the final step length is 1. Generally speaking, the simplest step size value is to take half of the array length for the first time as an increment, and then halve it each time until the increment is 1.
Algorithm Description
1. Choose an incremental sequence t1, t2,..., tk, where ti> tj, tk = 1;
2. According to the number of increment sequences k, sort the sequence k times;
3. In each sorting pass, according to the corresponding increment ti, the sequence to be sorted is divided into several sub-sequences of length m, and each sub-table is directly inserted and sorted. Only when the increment factor is 1, the entire sequence is treated as a table, and the length of the table is the length of the entire sequence.
Code
/**
* 希尔排序 针对有序序列在插入时采用交换法
*/
public static void ShellSort(int[] arr) {
//增量gap,并逐步缩小增量
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
//从第gap个元素,逐个对其所在组进行直接插入排序操作
for (int i = gap; i < arr.length; i++) {
int j = i;
while (j - gap >= 0 && arr[j] < arr[j - gap]) {
//插入排序采用交换法
swap(arr, j, j - gap);
j -= gap;
}
}
}
}
public static void swap(int[] arr, int a, int b) {
arr[a] = arr[a] + arr[b];
arr[b] = arr[a] - arr[b];
arr[a] = arr[a] - arr[b];
}
The reason why Hill sort is more efficient is that it weighs the size and order of sub-arrays. At the beginning of sorting, each sub-array is very short. After sorting, the sub-arrays are partially ordered. Both of these cases are suitable for insertion sort.
Six: Simple selection sort
Basic idea
Selection sort is a simple and intuitive sorting algorithm. It works as follows. First find the smallest (large) element in the unsorted sequence, store it at the beginning of the sorted sequence, and then continue to find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence. And so on, until all elements are sorted.
Algorithm Description
1. Find the element with the smallest key in the unsorted sequence
2. If the smallest element is not the first element of the unsorted sequence, swap it with the first element of the unsorted sequence
3. Repeat steps 1 and 2 until the end of the sequence.
Code
public static void SelectSort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int min = i;//默认从0开始的序号的值为最小值
//选出之后待排序中值最小的位置
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[j] < numbers[min]) {//比较值的大小,拿到序号
min = j;//拿到序号
}
}
//最小值不等于当前值时进行交换
if (min != i) {
int temp = numbers[i];
numbers[i] = numbers[min];
numbers[min] = temp;
}
}
}
//调用
int[] n = {60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87};
System.out.println(Arrays.toString(n));
SelectSort(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
The simplicity and intuitiveness of selection sorting is worthy of its name, which also makes it "famously slow". In either case, even if the original array has been sorted, it will take nearly n²/2 traversals to confirm it again. Even so, its sorting results are still unstable. The only good thing is that it does not consume additional memory space.
Seven: Heap Sort
The definition of a heap is as follows: a sequence of n elements {k1,k2,..,kn}
If and only if the following relationship is met, it is called a heap
Consider the two-dimensional array corresponding to this sequence as a complete binary tree. Then the meaning of heap is: the value of any non-leaf node in the complete binary tree is not greater than (or not less than) the value of its left and right child nodes. It can be seen from the above-mentioned properties that the top keyword of the large top pile is definitely the largest among all keywords, and the top keyword of the small top pile is the smallest among all keywords. So we can use the big top heap to sort in ascending order, and the small top heap to sort in descending order.
Basic idea
Take the big top pile as an example. The process of pile sorting is to construct the sequence to be sorted into a pile, select the largest one in the pile and remove it, then adjust the remaining elements into a pile, find the largest one and remove it, repeat Until orderly
Algorithm Description
1. First build the initial sequence K[1..n] into a large top pile, then the first element K1 is the largest at this time, and this pile is the initial disordered area.
2. Exchange the record K1 with the largest keyword (that is, the top of the heap, the first element) with the last record Kn of the disordered area, thereby obtaining a new disordered area K[1..n−1] and Sequence area K[n], and satisfy K[1..n−1].keys⩽K[n].key
3. After exchanging K1 and Kn, the top of the heap may violate the nature of the heap, so K[1..n−1] needs to be adjusted to the heap. Then repeat step 2 until there is only one element in the disordered area and stop.
Code
From the point of view of the algorithm description, heap sorting requires two processes, one is to build a heap, and the other is to exchange positions between the top of the heap and the last element of the heap. So heap sort consists of two functions. One is the function of building a heap, and the other is a function that calls the function of building a heap repeatedly to select the largest number of remaining unsorted elements to achieve sorting.
- Maximum heap adjustment (Max_Heapify): adjust the end child node of the heap so that the child node is always smaller than the parent node
- Create the maximum heap (Build_Max_Heap): reorder all data in the heap
- Heap Sort (HeapSort): Remove the root node of the first data, and do the recursive operation of the maximum heap adjustment
public static void HeapSort(int[] numbers) {
for (int i = numbers.length - 1; i > 0; i--) {
max_heapify(numbers, i);
//堆顶元素(第一个元素)与Kn交换
int temp = numbers[0];
numbers[0] = numbers[i];
numbers[i] = temp;
}
}
/***
*
* 将数组堆化
* i = 第一个非叶子节点。
* 从第一个非叶子节点开始即可。无需从最后一个叶子节点开始。
* 叶子节点可以看作已符合堆要求的节点,根节点就是它自己且自己以下值为最大。
*
* @param a
* @param n
*/
public static void max_heapify(int[] a, int n) {
int child;
for (int i = (n - 1) / 2; i >= 0; i--) {
//左子节点位置
child = 2 * i + 1;
//右子节点存在且大于左子节点,child变成右子节点
if (child != n && a[child] < a[child + 1]) {
child++;
}
//交换父节点与左右子节点中的最大值
if (a[i] < a[child]) {
int temp = a[i];
a[i] = a[child];
a[child] = temp;
}
}
}
//调用
int[] n = {60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87};
System.out.println(Arrays.toString(n));
HeapSort(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
Since the process of initializing the heap in heap sorting is more frequent, it is not suitable for small sequences. At the same time, due to multiple arbitrary subscript exchange positions, the original relative order between the same elements is destroyed, so it is an unstable sort.
Eight: merge sort
Merge sorting is an effective sorting algorithm based on merge operations. It was first proposed by John von Neumann in 1945. This algorithm is a very typical application of Divide and Conquer, and each layer of divide and conquer recursion can be performed at the same time.
Basic idea
The merge sort algorithm merges two (or more) ordered lists into a new ordered list, that is, divides the sequence to be sorted into several sub-sequences, and each sub-sequence is ordered. Then merge the ordered subsequences into the overall ordered sequence
Algorithm Description
Merge sort can be implemented in two ways:
- Top-down recursion
- Bottom-up iteration
Recursion method (assuming that the sequence has n elements in total):
1. Merge every two adjacent numbers in the sequence to form floor(n/2) sequences. After sorting, each sequence contains two elements;
2. Merge the above sequences again to form floor(n/4) sequences, each sequence contains four elements;
3. Repeat step 2 until all elements are sorted.
Iterative method
1. Apply for space so that its size is the sum of two sorted sequences. This space is used to store the merged sequence
2. Set two pointers, the initial positions are the starting positions of the two sorted sequences respectively
3. Compare the elements pointed to by the two pointers, select a relatively small element to put into the merge space, and move the pointer to the next position
4. Repeat step 3 until a pointer reaches the end of the sequence
5. Copy all the remaining elements of another sequence directly to the end of the merged sequence
Code
Merge sort actually does two things:
- Decomposition: Split the sequence in half each time
- Merge: sort and merge the divided sequence segments in pairs
Therefore, merge sort is actually two operations, split + merge
//归并所需的辅助数组
private static int[] aux;
public static void MergeSort(int[] numbers) {
//一次性分配空间
aux = new int[numbers.length];
sort(numbers, 0, numbers.length - 1);
}
public static void sort(int[] a, int low, int high) {
if (low >= high) {
return;
}
int mid = (low + high) / 2;
//将左半边排序
sort(a, low, mid);
//将右半边排序
sort(a, mid + 1, high);
merge(a, low, mid, high);
}
/**
* 该方法先将所有元素复制到aux[]中,然后在归并会a[]中。方法咋归并时(第二个for循环)
* 进行了4个条件判断:
* - 左半边用尽(取右半边的元素)
* - 右半边用尽(取左半边的元素)
* - 右半边的当前元素小于左半边的当前元素(取右半边的元素)
* - 右半边的当前元素大于等于左半边的当前元素(取左半边的元素)
* @param a
* @param low
* @param mid
* @param high
*/
public static void merge(int[] a, int low, int mid, int high) {
//将a[low..mid]和a[mid+1..high]归并
int i = low, j = mid + 1;
for (int k = low; k <= high; k++) {
aux[k] = a[k];
}
for (int k = low; k <= high; k++) {
if (i > mid) {
a[k] = aux[j++];
} else if (j > high) {
a[k] = aux[i++];
} else if (aux[j] < aux[i]) {
a[k] = aux[j++];
} else {
a[k] = aux[i++];
}
}
}
use
int[] n = {60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87};
System.out.println(Arrays.toString(n));
MergeSort(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
From the efficiency point of view, merge sort can be regarded as the "leading" in the sorting algorithm. Assuming that the length of the array is n, then the total of log n is required to split the array, and each step is an ordinary process of merging sub-arrays, and the time complexity It is O(n), so its comprehensive time complexity is O(nlogn). On the other hand, the sub-arrays split during multiple recursive processes of merge sort need to be stored in memory space, and the space complexity is O(n).
Nine: radix sort
Radix sort (Radix sort) is a non-comparative integer sorting algorithm. Its principle is to cut integers into different numbers by digits, and then compare them according to each digit. Since integers can also express strings (such as names or dates) and floating-point numbers in a specific format, radix sorting is not limited to integers.
Basic idea
It is implemented like this: all the values to be compared (positive integers) are unified to the same digit length, and the number with a shorter digit is filled with zeros in front. Then, starting from the lowest bit, sort one time in sequence. In this way, from the lowest order to the highest order, the sequence becomes an ordered sequence.
There are two implementation schemes for radix sorting according to priority from high or low order:
- MSD (Most significant digital) is sorted from the leftmost high bit. First sort the groups according to k1, record in the same group, the key code k1 is equal, and then sort each group into subgroups according to k2, and then continue this sorting and grouping of the following key codes, until the last key code kd is used for each group. After the subgroups are sorted, connect the groups to obtain an ordered sequence. The MSD method is suitable for sequences with many digits.
- LSD (Least significant digital) is sorted from the lowest bit on the far right. First start sorting from kd, then sort kd-1, repeat in turn, until k1 is sorted and an ordered sequence is obtained. The LSD method is suitable for sequences with a small number of digits.
Algorithm Description
Let's take LSD as an example, starting from the lowest bit, the specific algorithm is described as follows:
1. Get the largest number in the array and get the number of digits;
2. arr is the original array, and each bit is taken from the lowest bit to form a radix array;
3. Count and sort radix (using the characteristics of counting and sorting for small range numbers);
Code
Cardinality sorting: According to the value of each element in the sequence, the sorted N elements are "distributed" and "collected" several times to achieve sorting.
allocates : we take out the element in L[i], first determine the number in its units digit, and assign it to the bucket with the same sequence number according to the number
collection : When all the elements in the sequence are allocated to the corresponding buckets, the elements in the buckets are collected in order to form a new sequence to be sorted L[]. Repeat the allocation and collection of the tens and hundreds of elements in the newly formed sequence L[]... until the highest bit in the sequence is allocated, the sorting ends
public static void RadixSort(int[] arr) {
if (arr.length <= 1) return;
//取得数组中的最大数,并取得位数
int max = 0;
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
int maxDigit = 1;
while (max / 10 > 0) {
maxDigit++;
max = max / 10;
}
//申请一个桶空间
int[][] buckets = new int[10][arr.length];
int base = 10;
//从低位到高位,对每一位遍历,将所有元素分配到桶中
for (int i = 0; i < maxDigit; i++) {
int[] bktLen = new int[10]; //存储各个桶中存储元素的数量
//分配:将所有元素分配到桶中
for (int j = 0; j < arr.length; j++) {
int whichBucket = (arr[j] % base) / (base / 10);
buckets[whichBucket][bktLen[whichBucket]] = arr[j];
bktLen[whichBucket]++;
}
//收集:将不同桶里数据挨个捞出来,为下一轮高位排序做准备,由于靠近桶底的元素排名靠前,因此从桶底先捞
int k = 0;
for (int b = 0; b < buckets.length; b++) {
for (int p = 0; p < bktLen[b]; p++) {
arr[k++] = buckets[b][p];
}
}
System.out.println("Sorting: " + Arrays.toString(arr));
base *= 10;
}
}
use
int[] n = {60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87};
System.out.println(Arrays.toString(n));
RadixSort(n);
System.out.println(Arrays.toString(n));
//结果
System.out: [60, 38, 5, 14, 7, 23, 89, 77, 88, 4, 35, 45, 67, 99, 87]
System.out: Sorting: [60, 23, 14, 4, 5, 35, 45, 7, 77, 67, 87, 38, 88, 89, 99]
System.out: Sorting: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
System.out: [4, 5, 7, 14, 23, 35, 38, 45, 60, 67, 77, 87, 88, 89, 99]
Among them, d is the number of digits, r is the base, and n is the number of the original array. In radix sorting, because there is no comparison operation, in terms of complexity, the best case and the worst case are consistent in time, both of which are O(d*(n + r)).
: Human knowledge is limited
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。