-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProject6.java
More file actions
61 lines (53 loc) · 2.54 KB
/
Project6.java
File metadata and controls
61 lines (53 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//A program to compare five sorting algorithms: selection sort, insertion sort, heap sort, merge sort, and quick sort.
import java.util.*;
public class Project6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of words to sort:");
int numberOfWords = Integer.parseInt(scanner.nextLine());
String[] words = new String[numberOfWords];
System.out.println("Enter the words:");
for (int i = 0; i < numberOfWords; i++) {
words[i] = scanner.nextLine();
}
scanner.close();
Comparator<String> comparator = String::compareTo;
System.out.println("Algorithm | Comparisons | Time (Milliseconds)");
System.out.println("===================================================");
performSorts("Selection Sort", words, comparator);
performSorts("Insertion Sort", words, comparator);
performSorts("Heap Sort", words, comparator);
performSorts("Merge Sort", words, comparator);
performSorts("Quick Sort", words, comparator);
}
private static void performSorts(String sortName, String[] original, Comparator<String> comparator) {
String[] array = Arrays.copyOf(original, original.length);
long startTime = System.nanoTime(); // Start time in nanoseconds
long comparisons = 0;
switch (sortName) {
case "Selection Sort":
SelectionSort.sort(array, comparator);
comparisons = SelectionSort.getComparisons();
break;
case "Insertion Sort":
InsertionSort.sort(array, comparator);
comparisons = InsertionSort.getComparisons();
break;
case "Heap Sort":
HeapSort.sort(array, comparator);
comparisons = HeapSort.getComparisons();
break;
case "Merge Sort":
MergeSort.sort(array, comparator);
comparisons = MergeSort.getComparisons();
break;
case "Quick Sort":
QuickSort.sort(array, comparator);
comparisons = QuickSort.getComparisons();
break;
}
long endTime = System.nanoTime(); // End time in nanoseconds
double time = (endTime - startTime) / 1_000_000.0; // Convert nanoseconds to milliseconds with decimal
System.out.printf("%-15s | %10d | %10.3f ms\n", sortName, comparisons, time); // Print time with three decimal places
}
}