-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingAlgorithms.java
More file actions
88 lines (74 loc) · 2.61 KB
/
Copy pathSortingAlgorithms.java
File metadata and controls
88 lines (74 loc) · 2.61 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.Scanner;
public class SortingAlgorithms {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose sorting algorithm:");
System.out.println("1. Insertion Sort");
System.out.println("2. Selection Sort");
System.out.print("Enter your choice (1 or 2): ");
int choice = scanner.nextInt();
System.out.println("\nEnter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("\nEnter the elements: ");
for (int i = 0; i < n; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
arr[i] = scanner.nextInt();
}
System.out.println("\nArray before sorting: ");
printArray(arr);
System.out.println();
if (choice == 1) {
insertionSort(arr);
} else if (choice == 2) {
selectionSort(arr);
}
System.out.println("\nArray after sorting: ");
printArray(arr);
scanner.close();
}
// Insertion Sort
private static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = i;
while (j > 0 && arr[j-1] > arr[j]) {
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j = j-1;
}
System.out.println("Insertion Sort - Array after pass " + i + ": ");
printArray(arr);
System.out.println();
}
}
// Selection Sort
private static void selectionSort(int[] arr) {
for(int i = 0; i < arr.length; i++) {
int smallest = arr[i];
int smallestIndex = i;
for(int j = i; j < arr.length; j++) {
if (arr[j] < smallest) {
smallest = arr[j];
smallestIndex = j;
}
}
int temp = smallest;
arr[smallestIndex] = arr[i];
arr[i] = temp;
System.out.println("Selection Sort - Array after pass " + (i+1) + ": ");
printArray(arr);
System.out.println();
}
}
// Helper method to print array
private static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length - 1) {
System.out.print(" | ");
}
}
System.out.println();
}
}