Coding exercise 3
unknown
plain_text
10 months ago
8.1 kB
16
Indexable
import java.util.*;
public class SimpleSortingAlgorithmsComparison {
// Bubble Sort
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
// Insertion Sort
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
// Selection Sort
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) minIndex = j;
}
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
// Generate random array
public static int[] generateRandomArray(int size, int maxValue) {
int[] arr = new int[size];
Random rand = new Random();
for (int i = 0; i < size; i++) {
arr[i] = rand.nextInt(maxValue);
}
return arr;
}
// Copy array
public static int[] copyArray(int[] original) {
return Arrays.copyOf(original, original.length);
}
// Print array
public static void printArray(int[] arr) {
if (arr.length <= 20) {
System.out.println(Arrays.toString(arr));
} else {
System.out.print("[");
for (int i = 0; i < 10; i++) System.out.print(arr[i] + ", ");
System.out.print("... ");
for (int i = arr.length - 10; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length - 1) System.out.print(", ");
}
System.out.println("]");
}
}
// Check if sorted
public static boolean isSorted(int[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) return false;
}
return true;
}
// Perform sort
public static void performSort(String algorithmName, int[] arr, int algorithm) {
System.out.println("\n--- " + algorithmName + " ---");
long startTime = System.nanoTime();
switch (algorithm) {
case 1: bubbleSort(arr);
break;
case 2: insertionSort(arr);
break;
case 3:selectionSort(arr);
break;
}
long endTime = System.nanoTime();
double duration = (endTime - startTime) / 1_000_000.0;
System.out.println("Sorted array:");
printArray(arr);
System.out.println("Array is sorted: " + isSorted(arr));
System.out.printf("Time taken: %.3f ms%n", duration);
}
// Compare all
public static void compareAllAlgorithms(int[] originalArray) {
System.out.println("\n================================================");
System.out.println(" PERFORMANCE COMPARISON");
System.out.println("================================================");
double[] bubbleTimes = new double[3];
double[] insertionTimes = new double[3];
double[] selectionTimes = new double[3];
for (int run = 0; run < 3; run++) {
int[] arr1 = copyArray(originalArray);
long start = System.nanoTime();
bubbleSort(arr1);
long end = System.nanoTime();
bubbleTimes[run] = (end - start) / 1_000_000.0;
int[] arr2 = copyArray(originalArray);
start = System.nanoTime();
insertionSort(arr2);
end = System.nanoTime();
insertionTimes[run] = (end - start) / 1_000_000.0;
int[] arr3 = copyArray(originalArray);
start = System.nanoTime();
selectionSort(arr3);
end = System.nanoTime();
selectionTimes[run] = (end - start) / 1_000_000.0;
}
double bubbleAvg = Arrays.stream(bubbleTimes).average().orElse(0);
double insertionAvg = Arrays.stream(insertionTimes).average().orElse(0);
double selectionAvg = Arrays.stream(selectionTimes).average().orElse(0);
System.out.println("Algorithm | Avg Time (ms)");
System.out.println("----------------|---------------");
System.out.printf("Bubble Sort | %13.3f%n", bubbleAvg);
System.out.printf("Insertion Sort | %13.3f%n", insertionAvg);
System.out.printf("Selection Sort | %13.3f%n", selectionAvg);
String fastest = "Bubble Sort";
double fastestTime = bubbleAvg;
if (insertionAvg < fastestTime) { fastest = "Insertion Sort"; fastestTime = insertionAvg; }
if (selectionAvg < fastestTime) { fastest = "Selection Sort"; fastestTime = selectionAvg; }
System.out.println("\nFastest: " + fastest + " (" + fastestTime + " ms)");
}
// Main
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("================================================");
System.out.println(" SIMPLE SORTING ALGORITHMS COMPARISON");
System.out.println("================================================\n");
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
System.out.print("Enter the maximum value for array elements: ");
int maxValue = scanner.nextInt();
int[] originalArray = generateRandomArray(size, maxValue);
System.out.println("\nOriginal array:");
printArray(originalArray);
boolean continueProgram = true;
while (continueProgram) {
System.out.println("\n================================================");
System.out.println("Choose an option:");
System.out.println("1. Bubble Sort");
System.out.println("2. Insertion Sort");
System.out.println("3. Selection Sort");
System.out.println("4. Compare all algorithms");
System.out.println("5. Generate new array");
System.out.println("6. Exit");
System.out.print("Enter choice (1-6): ");
int choice = scanner.nextInt();
switch (choice) {
case 1 -> performSort("Bubble Sort", copyArray(originalArray), 1);
case 2 -> performSort("Insertion Sort", copyArray(originalArray), 2);
case 3 -> performSort("Selection Sort", copyArray(originalArray), 3);
case 4 -> compareAllAlgorithms(originalArray);
case 5 -> {
System.out.print("Enter new array size: ");
size = scanner.nextInt();
System.out.print("Enter maximum value: ");
maxValue = scanner.nextInt();
originalArray = generateRandomArray(size, maxValue);
System.out.println("\nNew array generated:");
printArray(originalArray);
}
case 6 -> {
continueProgram = false;
System.out.println("Exiting program. Goodbye!");
}
default -> System.out.println("Invalid choice. Try again.");
}
}
scanner.close();
}
}
Editor is loading...
Leave a Comment