Java implements selection sorting and visualizes each step iteration process

1. Overview of Select Sort Algorithm
Selection Sort is a simple and intuitive sorting algorithm. It works by selecting the smallest (or largest) element from the data element to be sorted each time and storing it at the start of the sequence until all elements are sorted.
Algorithm steps:
- Find the smallest (large) element in the unsorted sequence and store it at the start of the sorted sequence.
- Continue looking for the smallest (large) element from the remaining unsorted elements and place it at the end of the sorted sequence.
- Repeat the second step until all elements are sorted.
2. Basic selection sorting implementation
Here is a standard selection sorting Java implementation that contains some helper methods for array operations:
public class SelectionSortVisualizer {
/**
* Convert an integer array to a string representation for easy printing.
* For example: [1|2|3]
* @param a Array to be converted* @return The string representation of the array*/
private static String arrayToString(int[] a) {
String str = "[";
if (a.length > 0) {
str = a[0];
for (int i = 1; i <p> After the above main method executes the sort method, it will only print the final sort result, and it is impossible to intuitively see the change process of each iteration of the array.</p><h3> 3. Visualize each step iteration process</h3><p> To better understand the execution process of selecting sorting, we can print out the current state of the array immediately after each iteration (i.e., every execution of the main loop). This only requires a simple modification to the sort method.</p><p> <strong>Modification idea:</strong> In the main loop of the sort method for (int i = 0; i </p><pre class="brush:php;toolbar:false"> public class SelectionSortVisualizer {
// ... (arrayToString, swap, smallestPosFrom methods are the same as above, omitted here to keep it simple) ...
/**
* Sort the array selectively (ascending order) and print the array status after each step iteration.
* @param a Array to be sorted*/
public static void sort(int[] a) {
System.out.println("Start selection sort...");
for (int i = 0; i 0) {
str = a[0];
for (int i = 1; i <p> <strong>Run the sample output:</strong></p><pre class="brush:php;toolbar:false"> The original array is: [64|25|12|22|11]
Start selecting sorting...
Array status after step 1: [11|25|12|22|64]
Array status after step 2 iteration: [11|12|25|22|64]
Array status after step 3 iteration: [11|12|22|25|64]
Array status after step 4 iteration: [11|12|22|25|64]
Select Sort Complete.
Final sorting result: [11|12|22|25|64]From the output, we can see that after the first step iteration, the smallest element 11 is placed in the first position of the array. After the second step iteration, the smallest element 12 of the remaining elements is placed in the second position, and so on until the array is fully sorted.
4. Things to note
- Performance overhead: Printing operations in each iteration introduces additional I/O overhead. For small arrays, this overhead is negligible, but for very large arrays, frequent printing can significantly reduce the overall execution speed of the sorting algorithm. Therefore, this visualization method is mainly used for learning, demonstration and debugging purposes and is not recommended for performance-sensitive scenarios in production environments.
- Debugging and understanding: This step-by-step output method greatly helps developers understand the internal working mechanism of the algorithm. When there is a problem with the algorithm, you can locate the error faster by looking at the intermediate state.
- Log framework: In actual professional development, if you need to record the intermediate state of the algorithm, you usually use mature log frameworks (such as Log4j, SLF4J, etc.) instead of directly using System.out.println. The logging framework provides more flexible configurations (such as log levels, output targets, formats, etc.) for easy management and analysis.
5. Summary
By cleverly inserting a line of print statements into the core loop of the selection sorting algorithm, we successfully implemented step-by-step visualization of the sorting process. This method not only helps beginners understand the internal logic of selection sorting, but also provides an intuitive means for debugging complex algorithms. Despite some performance overhead, its value in the education and development stages is obvious. In actual projects, appropriate debugging and logging strategies should be selected based on specific needs and performance considerations.
The above is the detailed content of Java implements selection sorting and visualizes each step iteration process. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut
Aug 04, 2025 pm 12:48 PM
Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
What is a deadlock in Java and how can you prevent it?
Aug 23, 2025 pm 12:55 PM
AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree
How to join an array of strings in Java?
Aug 04, 2025 pm 12:55 PM
Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.
How to implement a simple TCP client in Java?
Aug 08, 2025 pm 03:56 PM
Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati
How to compare two strings in Java?
Aug 04, 2025 am 11:03 AM
Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.
How to send and receive messages over a WebSocket in Java
Aug 16, 2025 am 10:36 AM
Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe
Correct posture for handling non-UTF-8 request encoding in Spring Boot application
Aug 15, 2025 pm 12:30 PM
This article discusses the mechanism and common misunderstandings of Spring Boot applications for handling non-UTF-8 request encoding. The core lies in understanding the importance of the charset parameter in the HTTP Content-Type header, as well as the default character set processing flow of Spring Boot. By analyzing the garbled code caused by wrong testing methods, the article guides readers how to correctly simulate and test requests for different encodings, and explains that Spring Boot usually does not require complex configurations to achieve compatibility under the premise that the client correctly declares encoding.
Exploring Common Java Design Patterns with Examples
Aug 17, 2025 am 11:54 AM
The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.


