My Journey of Implementing a Sorting Algorithm Using Java
From Concept to Code: Unraveling the Path of Implementing a Sorting Algorithm in Java
Introduction:
In the world of computer science, sorting algorithms play a crucial role in organizing and arranging data efficiently. As an aspiring programmer, I embarked on a journey to implement a sorting algorithm using the versatile programming language, Java. In this article, I will share my experience, the challenges faced, and the steps I followed to create my sorting algorithm.
Understanding Sorting Algorithms:
Before diving into implementation, it was vital for me to comprehend the fundamental principles behind sorting algorithms. I researched various sorting techniques such as bubble sort, selection sort, insertion sort, merge sort and quicksort. Each algorithm had its advantages and trade-offs in terms of time complexity and space complexity.
Selecting the Sorting Algorithm:
After thorough research, I chose to implement four commonly used sorting algorithms: merge sort, selection sort, bubble sort, and insertion sort. Each of these algorithms has its unique characteristics and is widely used in different scenarios.
Implementation :
This Java program is a visual representation of a sorting algorithm. It creates a panel with a set number of bars, each representing an element to be sorted. The bars are initially randomly sized and colored. As the sorting algorithm progresses, the bars are rearranged and their colors change accordingly. The program utilizes the Swing framework for creating the graphical user interface. It provides methods to set the size of the sorting elements and repaint the panel to reflect the current state of the sorting process. Overall, it serves as a visual aid for understanding and observing the steps involved in this sorting algorithm.
Merge Sort:
This code implements the merge sort algorithm to sort an array of floating-point numbers. The main method is mergeSort()
, which initializes a SwingWorker
object and calls the mergeSortHelper()
method.
The mergeSortHelper()
method recursively divides the array into two halves until it reaches the base case (low >= high). Then it merges the two halves by calling the merge()
method.
The merge()
method takes three parameters: the low index, mid-index, and high index of the array. It calculates the sizes of the left and right subarrays and creates two temporary arrays to store the elements.
Next, it copies the elements from the original array into the left and right arrays. Then it performs a merging operation by comparing the elements from the left and right arrays and placing them in the original array in sorted order.
During the merging process, the code includes a sleep delay of 10 milliseconds and calls the repaint()
method. This allows for a visual representation of the sorting process in a graphical user interface (GUI). The sleep delay controls the speed at which the sorting animation is displayed.
Finally, any remaining elements in the left and right arrays are copied back into the original array.
In summary, the code recursively divides the array into smaller subarrays, merges them in sorted order, and visually represents the sorting process in a GUI.
Selection Sort:
Here's a breakdown of what's happening:
The
selectionSort
method initializes aSwingWorker
object calledsorter
. This object allows the sorting process to run in the background while the user interface remains responsive.Within the
doInBackground
method ofsorter
, the selection sort algorithm is implemented using nested loops. The outer loop iterates over each element in the array, except for the last one.Inside the outer loop, the
min_index
variable is initialized with the current index. The inner loop starts from the next index and searches for the minimum value in the remaining unsorted portion of the array. If a smaller value is found, themin_index
is updated.After finding the minimum value, the
swap
method is called to swap the elements atcurrent_index
andmin_index
, effectively placing the smallest element in its correct position.The code then introduces a small delay of 10 milliseconds using
Thread.sleep(10)
to control the sorting speed.The
repaint
method is called to update the visual representation of the array after each swap. This is necessary because the contents of a JPanel are frequently replaced during the sorting process.Once the sorting is complete, the
current_index
andtraversing_index
variables are reset to zero.Finally, the method returns
null
, as thedoInBackground
method is expected to return a value ofVoid
type.
In short, the code uses the selection sort algorithm to sort an array of bar heights visually, with each iteration swapping the smallest element with the current index. The sorting process occurs in the background, allowing the user interface to remain responsive, and the visual representation of the array is updated after each swap.
Bubble Sort:
In this code I defined a method called bubbleSort()
that implements the bubble sort algorithm to sort an array of bar_height
values. The method uses a SwingWorker
object to perform the sorting operation in a background thread.
The algorithm iterates over the array elements using two nested loops. The outer loop, controlled by the current_index
variable, represents the number of passes through the array. The inner loop, controlled by the traversing_index
variable, compares adjacent elements and swaps them if they are in the wrong order.
If a swap is performed, the swap()
method is called to exchange the values and update the indices accordingly. Then, the traversing_index
is decremented to ensure the swapped elements are rechecked in the next iteration.
After each swap, there is a delay of 10 milliseconds introduced by Thread.sleep(10)
, which controls the speed of the sorting animation. The repaint()
method is called to update the graphical representation of the sorting process.
Once the sorting is complete, the current_index
and traversing_index
variables are reset to 0, and the method returns null
.
In summary, the code implements the bubble sort algorithm using a background thread and provides a visual animation of the sorting process.
Insertion Sort:
The bubbleSort()
method initializes a SwingWorker
object called sorter
. The sorter
is defined as an anonymous inner class that extends SwingWorker<Void>
, indicating that it doesn't return any result upon completion.
The sorting algorithm itself is implemented in the doInBackground()
method, which is executed in a background thread. Here's how the algorithm works:
The outer loop iterates over each element in the array, represented by the
current_index
variable. It starts from 0 and goes up to the last index.Inside the outer loop, the inner loop compares adjacent elements and swaps them if they are in the wrong order. The
traversing_index
variable represents the current index being traversed in the inner loop. It starts at 1 and goes up to(getSIZE() - current_index) - 1
. The- current_index
is used because, in each iteration of the outer loop, the largest element gets bubbled up to the end, so there's no need to compare it again.If the current element (
bar_height[traversing_index]
) is smaller than the previous element (bar_height[traversing_index - 1]
), a swap is performed by calling theswap()
method. This method exchanges the positions of the two elements.After the swap,
traversing_index
is decremented by 1. This is done to control the animation of the sorting process. By decrementing the index, the loop will revisit the same element, which provides the effect of the bar moving backward before settling into its sorted position.A
Thread.sleep(10)
statement introduces a 10-millisecond delay after each swap. This controls the speed of the sorting animation, allowing the user to visualize the sorting process.The
repaint()
method is called to update the graphical representation of the bars on the screen. It triggers the repainting of the component to reflect the new order of the bars after each swap.Once the sorting process is completed,
current_index
andtraversing_index
are reset to 0.Finally,
null
is returned as the result of thedoInBackground()
method since it has aVoid
return type.
In summary, this code implements the bubble sort algorithm by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The sorting process is executed asynchronously using a
SwingWorker
, allowing for smooth animation and responsiveness of the user interface during the sorting operation
Suffering the bars:
The code snippet represents a method called initShuffler()
that shuffles a set of bars visually represented on a JPanel. It uses a SwingWorker to perform the shuffling in the background while allowing the UI to remain responsive. The shuffling process involves swapping the positions of bars randomly, controlled by a speed parameter. After the shuffling is complete, it triggers another task called sorter
to execute.
Additionally, there is another method called initBarHeight()
that initializes the heights of the bars based on a given size. It calculates the interval between each bar's height based on the total height available.
Finally, the swap()
method is responsible for swapping the heights of two bars given their indices. It uses a temporary variable to hold the value of one bar's height, performs the swap, and updates the heights accordingly.
GUI:
This code represents the main graphical user interface (GUI) for a sorting visualization. It includes panels, buttons, a progress bar, and a slider for selecting sorting techniques, speed, and array size. To design this GUI I used Swing components. The user can choose different sorting algorithms such as merge sort, bubble sort, insertion sort, and selection sort. There is a "Randomize" button to shuffle the array, and a "Start" button to initiate the sorting process. The slider allows to adjust the size of the array.
Testing and Refinement:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SortingAlgorithmTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(SortingAlgorithmTest::createAndShowGUI);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Sorting Algorithm Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SortingAlgorithm sortingAlgorithm = new SortingAlgorithm();
sortingAlgorithm.initShuffler(); // Shuffle the bars initially
frame.add(sortingAlgorithm);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
In this test application, I created a JFrame
and add an instance of SortingAlgorithm
to it. I then invoke the initShuffler()
method to shuffle the bars initially. Finally, display the frame.
I compiled and run this code to see the sorting algorithm in action. I further refine the application by adding buttons or a dropdown menu to select different sorting algorithms and trigger their execution.
Finished look:
Skills Gained
Multi-Threading using Swing Worker
Customizing Swing Components
Working with Graphics 2D
Different sorting algorithms
Conclusion:
Implementing a sorting algorithm using Java has been an enlightening and fulfilling experience. It not only deepened my understanding of fundamental sorting techniques but also enhanced my programming skills. By following the steps above, I successfully implemented the bubble sort algorithm in Java. I encourage fellow programmers to explore various sorting algorithms and attempt their own implementations, as it offers valuable insights into algorithmic thinking and problem-solving.
References:
https://stackoverflow.com/questions/31094904/jmenu-not-appearing-until-window-is-resized
https://stackoverflow.com/questions/4716372/java-how-do-i-close-a-jframe-while-opening-another-one
https://stackoverflow.com/questions/4246351/creating-random-colour-in-java
https://stackoverflow.com/questions/782265/how-do-i-use-swingworker-in-java
https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
https://stackoverflow.com/questions/1097366/java-swing-revalidate-vs-repaint