Java Exercise
In this exercise, you will create a Java program that implements several programming and code optimization best practices. The goal is to write clean and efficient code, applying techniques such as complexity reduction, readability improvement, and algorithm optimization. You will work with common data structures and algorithms, ensuring that your code is easy to maintain, understand, and execute efficiently.
Instructions:
- Write a program that solves a common problem (e.g., sorting a list of items) using an efficient algorithm.
- Apply optimization techniques, such as improving memory usage and runtime.
- Refactor your code, ensuring it is readable, modular, and well-commented.
- Perform performance tests to compare the performance of your implementation before and after optimization.
This exercise will help you improve your skills in writing optimized and clean code, following development best practices for high-performance Java applications.
View Example Code
import java.util.Arrays;
public class OptimizedSorting {
// Method to perform the QuickSort algorithm
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
int pivotIndex = partition(array, low, high);
quickSort(array, low, pivotIndex - 1); // Sort the left part
quickSort(array, pivotIndex + 1, high); // Sort the right part
}
}
// Method to partition the array
public static int partition(int[] array, int low, int high) {
int pivot = array[high]; // The last element is the pivot
int i = (low - 1);
for (int j = low; j < high; j++) {
// If the current element is smaller than the pivot
if (array[j] < pivot) {
i++;
// Swap the elements
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Swap the pivot with the element at the correct position
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
// Main method to execute the program
public static void main(String[] args) {
int[] numbers = { 12, 11, 13, 5, 6, 7 };
System.out.println("Original array: " + Arrays.toString(numbers));
// Call the optimized sorting algorithm
long start = System.nanoTime(); // Measure start time
quickSort(numbers, 0, numbers.length - 1);
long end = System.nanoTime(); // Measure end time
// Display the sorted array
System.out.println("Sorted array: " + Arrays.toString(numbers));
// Display execution time
System.out.println("Execution time (in nanoseconds): " + (end - start));
}
}
Output:
Original array: [12, 11, 13, 5, 6, 7]
Sorted array: [5, 6, 7, 11, 12, 13]
Execution time (in nanoseconds): 21423
This program implements the **QuickSort** algorithm, one of the best solutions for sorting arrays due to its runtime efficiency in most cases. By optimizing the code, it becomes more efficient in both memory and time, and it is refactored to be modular and easy to understand.