mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -11,9 +11,9 @@ import java.util.*;
|
||||
public class bubble_sort {
|
||||
/* Bubble sort */
|
||||
static void bubbleSort(int[] nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (int i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
@@ -27,31 +27,31 @@ public class bubble_sort {
|
||||
|
||||
/* Bubble sort (flag optimization) */
|
||||
static void bubbleSortWithFlag(int[] nums) {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
// Outer loop: the unsorted range is [0, i]
|
||||
for (int i = nums.length - 1; i > 0; i--) {
|
||||
boolean flag = false; // Initialize flag
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
boolean flag = false; // Initialize the flag
|
||||
// Inner loop: move the largest element in the unsorted range [0, i] to its right end through swaps
|
||||
for (int j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
int tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true; // Record element swap
|
||||
flag = true; // Record that a swap occurred
|
||||
}
|
||||
}
|
||||
if (!flag)
|
||||
break; // No elements were swapped in this round of "bubbling", exit directly
|
||||
break; // Exit immediately if this pass made no swaps
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] nums = { 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSort(nums);
|
||||
System.out.println("After bubble sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After bubble sort, nums = " + Arrays.toString(nums));
|
||||
|
||||
int[] nums1 = { 4, 1, 3, 1, 5, 2 };
|
||||
bubbleSortWithFlag(nums1);
|
||||
System.out.println("After bubble sort completes, nums1 = " + Arrays.toString(nums1));
|
||||
System.out.println("After bubble sort, nums1 = " + Arrays.toString(nums1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,25 +11,25 @@ import java.util.*;
|
||||
public class bucket_sort {
|
||||
/* Bucket sort */
|
||||
static void bucketSort(float[] nums) {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
// Initialize k = n/2 buckets, expecting 2 elements per bucket
|
||||
int k = nums.length / 2;
|
||||
List<List<Float>> buckets = new ArrayList<>();
|
||||
for (int i = 0; i < k; i++) {
|
||||
buckets.add(new ArrayList<>());
|
||||
}
|
||||
// 1. Distribute array elements into various buckets
|
||||
// 1. Distribute the array elements among the buckets
|
||||
for (float num : nums) {
|
||||
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
|
||||
// The input range is [0, 1); use num * k to map each value to an index in [0, k-1]
|
||||
int i = (int) (num * k);
|
||||
// Add num to bucket i
|
||||
buckets.get(i).add(num);
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for (List<Float> bucket : buckets) {
|
||||
// Use built-in sorting function, can also replace with other sorting algorithms
|
||||
// Use the built-in sorting function, or replace it with another sorting algorithm
|
||||
Collections.sort(bucket);
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
// 3. Traverse the buckets to combine the results
|
||||
int i = 0;
|
||||
for (List<Float> bucket : buckets) {
|
||||
for (float num : bucket) {
|
||||
@@ -39,9 +39,9 @@ public class bucket_sort {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Assume input data is floating point, interval [0, 1)
|
||||
// Assume the input consists of floating-point numbers in [0, 1)
|
||||
float[] nums = { 0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f };
|
||||
bucketSort(nums);
|
||||
System.out.println("After bucket sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After bucket sort, nums = " + Arrays.toString(nums));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,20 +10,20 @@ import java.util.*;
|
||||
|
||||
public class counting_sort {
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
// Simple implementation; cannot be used to sort objects
|
||||
static void countingSortNaive(int[] nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
// 1. Find the maximum array element m
|
||||
int m = 0;
|
||||
for (int num : nums) {
|
||||
m = Math.max(m, num);
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
int[] counter = new int[m + 1];
|
||||
for (int num : nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
// 3. Traverse counter and fill the original array nums with the elements
|
||||
int i = 0;
|
||||
for (int num = 0; num < m + 1; num++) {
|
||||
for (int j = 0; j < counter[num]; j++, i++) {
|
||||
@@ -33,34 +33,34 @@ public class counting_sort {
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
// Full implementation; stable and adaptable to sorting objects
|
||||
static void countingSort(int[] nums) {
|
||||
// 1. Count the maximum element m in the array
|
||||
// 1. Find the maximum array element m
|
||||
int m = 0;
|
||||
for (int num : nums) {
|
||||
m = Math.max(m, num);
|
||||
}
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
// 2. Count the occurrences of each number
|
||||
// counter[num] is the number of occurrences of num
|
||||
int[] counter = new int[m + 1];
|
||||
for (int num : nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// counter[num]-1 is the last index where num appears in res
|
||||
// 3. Compute prefix sums of counter to convert occurrence counts into end positions
|
||||
// That is, counter[num]-1 is the index of the last occurrence of num in res
|
||||
for (int i = 0; i < m; i++) {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. Traverse nums in reverse order, placing each element into the result array res
|
||||
// Initialize the array res to record results
|
||||
// 4. Traverse nums in reverse and place each element in the result array res
|
||||
// Initialize array res to store the result
|
||||
int n = nums.length;
|
||||
int[] res = new int[n];
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int num = nums[i];
|
||||
res[counter[num] - 1] = num; // Place num at the corresponding index
|
||||
counter[num]--; // Decrement the prefix sum by 1, getting the next index to place num
|
||||
counter[num]--; // Decrement the prefix sum by 1 to determine where to place the next occurrence of num
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
// Overwrite the original array nums with the result array res
|
||||
for (int i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
@@ -69,10 +69,10 @@ public class counting_sort {
|
||||
public static void main(String[] args) {
|
||||
int[] nums = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
|
||||
countingSortNaive(nums);
|
||||
System.out.println("After counting sort (cannot sort objects) completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After counting sort (does not support objects), nums = " + Arrays.toString(nums));
|
||||
|
||||
int[] nums1 = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
|
||||
countingSort(nums1);
|
||||
System.out.println("After counting sort completes, nums1 = " + Arrays.toString(nums1));
|
||||
System.out.println("After counting sort, nums1 = " + Arrays.toString(nums1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,10 +9,10 @@ package chapter_sorting;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class heap_sort {
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
/* Sift down from node i in a heap of size n */
|
||||
public static void siftDown(int[] nums, int n, int i) {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
int l = 2 * i + 1;
|
||||
int r = 2 * i + 2;
|
||||
int ma = i;
|
||||
@@ -20,31 +20,31 @@ public class heap_sort {
|
||||
ma = l;
|
||||
if (r < n && nums[r] > nums[ma])
|
||||
ma = r;
|
||||
// Swap two nodes
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma == i)
|
||||
break;
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
int temp = nums[i];
|
||||
nums[i] = nums[ma];
|
||||
nums[ma] = temp;
|
||||
// Loop downwards heapification
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
public static void heapSort(int[] nums) {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
// Build the heap by sifting down from every non-leaf node
|
||||
for (int i = nums.length / 2 - 1; i >= 0; i--) {
|
||||
siftDown(nums, nums.length, i);
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
// Extract the largest element from the heap, repeating for n-1 rounds
|
||||
for (int i = nums.length - 1; i > 0; i--) {
|
||||
// Delete node
|
||||
// Swap the root with the rightmost leaf on the last level (the first and last elements of the current heap)
|
||||
int tmp = nums[0];
|
||||
nums[0] = nums[i];
|
||||
nums[i] = tmp;
|
||||
// Start heapifying the root node, from top to bottom
|
||||
// Sift down starting at the root
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,6 @@ public class heap_sort {
|
||||
public static void main(String[] args) {
|
||||
int[] nums = { 4, 1, 3, 1, 5, 2 };
|
||||
heapSort(nums);
|
||||
System.out.println("After heap sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After heap sort, nums = " + Arrays.toString(nums));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,21 +11,21 @@ import java.util.*;
|
||||
public class insertion_sort {
|
||||
/* Insertion sort */
|
||||
static void insertionSort(int[] nums) {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
// Outer loop: the sorted range is [0, i-1]
|
||||
for (int i = 1; i < nums.length; i++) {
|
||||
int base = nums[i], j = i - 1;
|
||||
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
|
||||
// Inner loop: insert base at the correct position in the sorted range [0, i-1]
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
|
||||
nums[j + 1] = nums[j]; // Shift nums[j] one position to the right
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = base; // Assign base to the correct position
|
||||
nums[j + 1] = base; // Place base at the correct position
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] nums = { 4, 1, 3, 1, 5, 2 };
|
||||
insertionSort(nums);
|
||||
System.out.println("After insertion sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After insertion sort, nums = " + Arrays.toString(nums));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ package chapter_sorting;
|
||||
import java.util.*;
|
||||
|
||||
public class merge_sort {
|
||||
/* Merge left subarray and right subarray */
|
||||
/* Merge the left and right subarrays */
|
||||
static void merge(int[] nums, int left, int mid, int right) {
|
||||
// Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged results
|
||||
// The left subarray spans [left, mid], and the right subarray spans [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged result
|
||||
int[] tmp = new int[right - left + 1];
|
||||
// Initialize the start indices of the left and right subarrays
|
||||
// Initialize the starting indices of the left and right subarrays
|
||||
int i = left, j = mid + 1, k = 0;
|
||||
// While both subarrays still have elements, compare and copy the smaller element into the temporary array
|
||||
// While both subarrays have elements remaining, compare them and copy the smaller element into the temporary array
|
||||
while (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j])
|
||||
tmp[k++] = nums[i++];
|
||||
@@ -30,7 +30,7 @@ public class merge_sort {
|
||||
while (j <= right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// Copy the elements from the temporary array tmp back to the original array nums at the corresponding interval
|
||||
// Copy the elements of temporary array tmp back into the corresponding range of the original array nums
|
||||
for (k = 0; k < tmp.length; k++) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
@@ -38,14 +38,14 @@ public class merge_sort {
|
||||
|
||||
/* Merge sort */
|
||||
static void mergeSort(int[] nums, int left, int right) {
|
||||
// Termination condition
|
||||
// Base case
|
||||
if (left >= right)
|
||||
return; // Terminate recursion when subarray length is 1
|
||||
// Divide and conquer stage
|
||||
int mid = left + (right - left) / 2; // Calculate midpoint
|
||||
mergeSort(nums, left, mid); // Recursively process the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recursively process the right subarray
|
||||
// Merge stage
|
||||
return; // Stop recursing when the subarray has at most one element
|
||||
// Divide phase
|
||||
int mid = left + (right - left) / 2; // Calculate the midpoint
|
||||
mergeSort(nums, left, mid); // Recurse on the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recurse on the right subarray
|
||||
// Merge phase
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
@@ -53,6 +53,6 @@ public class merge_sort {
|
||||
/* Merge sort */
|
||||
int[] nums = { 7, 3, 2, 6, 0, 1, 5, 4 };
|
||||
mergeSort(nums, 0, nums.length - 1);
|
||||
System.out.println("After merge sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After merge sort, nums = " + Arrays.toString(nums));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,36 +10,36 @@ import java.util.*;
|
||||
|
||||
/* Quick sort class */
|
||||
class QuickSort {
|
||||
/* Swap elements */
|
||||
/* Swap the elements */
|
||||
static void swap(int[] nums, int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
/* Two-pointer partitioning */
|
||||
static int partition(int[] nums, int left, int right) {
|
||||
// Use nums[left] as the pivot
|
||||
int i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // Search from right to left for the first element smaller than the pivot
|
||||
j--; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // Search from left to right for the first element greater than the pivot
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
public static void quickSort(int[] nums, int left, int right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
// Stop recursing when the subarray has at most one element
|
||||
if (left >= right)
|
||||
return;
|
||||
// Sentinel partition
|
||||
// Two-pointer partitioning
|
||||
int pivot = partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class QuickSort {
|
||||
|
||||
/* Quick sort class (median pivot optimization) */
|
||||
class QuickSortMedian {
|
||||
/* Swap elements */
|
||||
/* Swap the elements */
|
||||
static void swap(int[] nums, int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
@@ -58,39 +58,39 @@ class QuickSortMedian {
|
||||
static int medianThree(int[] nums, int left, int mid, int right) {
|
||||
int l = nums[left], m = nums[mid], r = nums[right];
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l))
|
||||
return mid; // m is between l and r
|
||||
return mid; // m lies between l and r
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m))
|
||||
return left; // l is between m and r
|
||||
return left; // l lies between m and r
|
||||
return right;
|
||||
}
|
||||
|
||||
/* Sentinel partition (median of three) */
|
||||
/* Two-pointer partitioning (median of three) */
|
||||
static int partition(int[] nums, int left, int right) {
|
||||
// Select the median of three candidate elements
|
||||
int med = medianThree(nums, left, (left + right) / 2, right);
|
||||
// Swap the median to the array's leftmost position
|
||||
// Swap the median into the leftmost position of the current subarray
|
||||
swap(nums, left, med);
|
||||
// Use nums[left] as the pivot
|
||||
int i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // Search from right to left for the first element smaller than the pivot
|
||||
j--; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // Search from left to right for the first element greater than the pivot
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
public static void quickSort(int[] nums, int left, int right) {
|
||||
// Terminate recursion when subarray length is 1
|
||||
// Stop recursing when the subarray has at most one element
|
||||
if (left >= right)
|
||||
return;
|
||||
// Sentinel partition
|
||||
// Two-pointer partitioning
|
||||
int pivot = partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
// Recurse on the left and right subarrays
|
||||
quickSort(nums, left, pivot - 1);
|
||||
quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
@@ -98,41 +98,41 @@ class QuickSortMedian {
|
||||
|
||||
/* Quick sort class (recursion depth optimization) */
|
||||
class QuickSortTailCall {
|
||||
/* Swap elements */
|
||||
/* Swap the elements */
|
||||
static void swap(int[] nums, int i, int j) {
|
||||
int tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
/* Two-pointer partitioning */
|
||||
static int partition(int[] nums, int left, int right) {
|
||||
// Use nums[left] as the pivot
|
||||
int i = left, j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left])
|
||||
j--; // Search from right to left for the first element smaller than the pivot
|
||||
j--; // Scan from right to left for the first element smaller than the pivot
|
||||
while (i < j && nums[i] <= nums[left])
|
||||
i++; // Search from left to right for the first element greater than the pivot
|
||||
i++; // Scan from left to right for the first element larger than the pivot
|
||||
swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
swap(nums, i, left); // Swap the pivot into the boundary position between the two subarrays
|
||||
return i; // Return the pivot index
|
||||
}
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
public static void quickSort(int[] nums, int left, int right) {
|
||||
// Terminate when subarray length is 1
|
||||
// Stop when the subarray has at most one element
|
||||
while (left < right) {
|
||||
// Sentinel partition operation
|
||||
// Perform two-pointer partitioning
|
||||
int pivot = partition(nums, left, right);
|
||||
// Perform quick sort on the shorter of the two subarrays
|
||||
// Apply quick sort to the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
quickSort(nums, left, pivot - 1); // Recursively sort the left subarray
|
||||
left = pivot + 1; // Remaining unsorted interval is [pivot + 1, right]
|
||||
left = pivot + 1; // The remaining unsorted range is [pivot + 1, right]
|
||||
} else {
|
||||
quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // Remaining unsorted interval is [left, pivot - 1]
|
||||
right = pivot - 1; // The remaining unsorted range is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,16 +143,16 @@ public class quick_sort {
|
||||
/* Quick sort */
|
||||
int[] nums = { 2, 4, 1, 0, 3, 5 };
|
||||
QuickSort.quickSort(nums, 0, nums.length - 1);
|
||||
System.out.println("After quick sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After quick sort, nums = " + Arrays.toString(nums));
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
/* Quick sort (median pivot optimization) */
|
||||
int[] nums1 = { 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortMedian.quickSort(nums1, 0, nums1.length - 1);
|
||||
System.out.println("After quick sort (median pivot optimization) completes, nums1 = " + Arrays.toString(nums1));
|
||||
System.out.println("After quick sort (median pivot optimization), nums1 = " + Arrays.toString(nums1));
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
int[] nums2 = { 2, 4, 1, 0, 3, 5 };
|
||||
QuickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
|
||||
System.out.println("After quick sort (recursion depth optimization) completes, nums2 = " + Arrays.toString(nums2));
|
||||
System.out.println("After quick sort (recursion depth optimization), nums2 = " + Arrays.toString(nums2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,52 +9,52 @@ package chapter_sorting;
|
||||
import java.util.*;
|
||||
|
||||
public class radix_sort {
|
||||
/* Get the k-th digit of element num, where exp = 10^(k-1) */
|
||||
/* Get the k-th digit of num, where exp = 10^(k-1) */
|
||||
static int digit(int num, int exp) {
|
||||
// Passing exp instead of k can avoid repeated expensive exponentiation here
|
||||
// Passing exp instead of k avoids repeatedly performing expensive exponentiation here
|
||||
return (num / exp) % 10;
|
||||
}
|
||||
|
||||
/* Counting sort (based on nums k-th digit) */
|
||||
/* Counting sort (sort nums by the k-th digit) */
|
||||
static void countingSortDigit(int[] nums, int exp) {
|
||||
// Decimal digit range is 0~9, therefore need a bucket array of length 10
|
||||
// Decimal digits range from 0 to 9, so the bucket array needs length 10
|
||||
int[] counter = new int[10];
|
||||
int n = nums.length;
|
||||
// Count the occurrence of digits 0~9
|
||||
// Count the occurrences of each digit from 0 to 9
|
||||
for (int i = 0; i < n; i++) {
|
||||
int d = digit(nums[i], exp); // Get the k-th digit of nums[i], noted as d
|
||||
counter[d]++; // Count the occurrence of digit d
|
||||
int d = digit(nums[i], exp); // Get the k-th digit of nums[i] and store it in d
|
||||
counter[d]++; // Count the occurrences of digit d
|
||||
}
|
||||
// Calculate prefix sum, converting "occurrence count" into "array index"
|
||||
// Compute prefix sums to convert occurrence counts into array positions
|
||||
for (int i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse, based on bucket statistics, place each element into res
|
||||
// Traverse in reverse and place each element into res according to the bucket counts
|
||||
int[] res = new int[n];
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
int d = digit(nums[i], exp);
|
||||
int j = counter[d] - 1; // Get the index j for d in the array
|
||||
int j = counter[d] - 1; // Get the destination index j for digit d in the array
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d]--; // Decrease the count of d by 1
|
||||
counter[d]--; // Decrease the count for d by 1
|
||||
}
|
||||
// Use result to overwrite the original array nums
|
||||
// Overwrite the original array nums with the result
|
||||
for (int i = 0; i < n; i++)
|
||||
nums[i] = res[i];
|
||||
}
|
||||
|
||||
/* Radix sort */
|
||||
static void radixSort(int[] nums) {
|
||||
// Get the maximum element of the array, used to determine the maximum number of digits
|
||||
// Get the largest array element to determine the maximum number of digits
|
||||
int m = Integer.MIN_VALUE;
|
||||
for (int num : nums)
|
||||
if (num > m)
|
||||
m = num;
|
||||
// Traverse from the lowest to the highest digit
|
||||
// Process digits from least significant to most significant
|
||||
for (int exp = 1; exp <= m; exp *= 10) {
|
||||
// Perform counting sort on the k-th digit of array elements
|
||||
// Apply counting sort to the k-th digit of the array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// i.e., exp = 10^(k-1)
|
||||
// That is, exp = 10^(k-1)
|
||||
countingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,6 @@ public class radix_sort {
|
||||
int[] nums = { 10546151, 35663510, 42865989, 34862445, 81883077,
|
||||
88906420, 72429244, 30524779, 82060337, 63832996 };
|
||||
radixSort(nums);
|
||||
System.out.println("After radix sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After radix sort, nums = " + Arrays.toString(nums));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,15 +12,15 @@ public class selection_sort {
|
||||
/* Selection sort */
|
||||
public static void selectionSort(int[] nums) {
|
||||
int n = nums.length;
|
||||
// Outer loop: unsorted interval is [i, n-1]
|
||||
// Outer loop: the unsorted range is [i, n-1]
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
// Inner loop: find the smallest element within the unsorted interval
|
||||
// Inner loop: find the smallest element in the unsorted range
|
||||
int k = i;
|
||||
for (int j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k])
|
||||
k = j; // Record the index of the smallest element
|
||||
}
|
||||
// Swap the smallest element with the first element of the unsorted interval
|
||||
// Swap the smallest element with the first element of the unsorted range
|
||||
int temp = nums[i];
|
||||
nums[i] = nums[k];
|
||||
nums[k] = temp;
|
||||
@@ -30,6 +30,6 @@ public class selection_sort {
|
||||
public static void main(String[] args) {
|
||||
int[] nums = { 4, 1, 3, 1, 5, 2 };
|
||||
selectionSort(nums);
|
||||
System.out.println("After selection sort completes, nums = " + Arrays.toString(nums));
|
||||
System.out.println("After selection sort, nums = " + Arrays.toString(nums));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user