如何在Java选择排序(Selection Sort)中显示每轮排序过程
Solution
Here's the modified code that prints each pass of the sorting process, along with key explanations:
import java.util.Scanner; public class SelectionSortWithPasses { public static void main(String[] args) { Scanner ss = new Scanner(System.in); int a, j, temp; int arr[] = new int[50]; // Input number of elements System.out.print("Input a number: "); int num = ss.nextInt(); System.out.println(); // Input array elements for (a = 0; a < num; a++) { System.out.print("a[" + a + "]: "); arr[a] = ss.nextInt(); } // Print unsorted array System.out.print("\nUnSorted Array: "); printArray(arr, num); // Selection sort with pass printing for (a = 0; a < num; a++) { // Inner loop to compare and swap elements (your original logic) for (j = a + 1; j < num; j++) { if (arr[a] > arr[j]) { temp = arr[a]; arr[a] = arr[j]; arr[j] = temp; } } // Print current pass state int passNumber = a + 1; System.out.print(passNumber + getOrdinalSuffix(passNumber) + " Pass: "); printArray(arr, num); } // Print sorted array System.out.print("Sorted Array Values :"); printArray(arr, num); ss.close(); } // Helper method to print array elements (avoids code duplication) private static void printArray(int[] arr, int length) { for (int i = 0; i < length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } // Helper method to generate ordinal suffixes (1st, 2nd, 3rd, etc.) private static String getOrdinalSuffix(int number) { if (number >= 11 && number <= 13) { return "th"; } switch (number % 10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; default: return "th"; } } }
Key Changes:
Added Helper Methods:
printArray: Reusable function to print array elements, used for unsorted, pass-by-pass, and sorted output.getOrdinalSuffix: Generates correct suffixes for pass numbers to match your expected format.
Pass-by-Pass Printing:
- After each iteration of the outer sorting loop, we print the current state of the array with the appropriate 1-based pass label.
Formatting & Cleanup:
- Added newlines to match the spacing in your expected output.
- Closed the
Scannerto prevent resource leaks.
Optional: Standard Selection Sort
Your current code swaps elements immediately when a smaller value is found. For the standard selection sort (find the minimum element first, then swap once per pass), replace the sorting loop with this code:
for (a = 0; a < num - 1; a++) { int minIndex = a; // Find index of the smallest element in the unsorted portion for (j = a + 1; j < num; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } // Swap only if a smaller element was found if (minIndex != a) { temp = arr[a]; arr[a] = arr[minIndex]; arr[minIndex] = temp; } // Print current pass int passNumber = a + 1; System.out.print(passNumber + getOrdinalSuffix(passNumber) + " Pass: "); printArray(arr, num); }
内容的提问来源于stack exchange,提问作者Ellie Riggs
相关产品推荐
相关产品推荐

