-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP30_BubbleSortAndSelectionSort.java
More file actions
61 lines (55 loc) · 1.97 KB
/
Copy pathP30_BubbleSortAndSelectionSort.java
File metadata and controls
61 lines (55 loc) · 1.97 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
package programs;
import java.util.Arrays;
/**
* ============================================================
* PROGRAM 30: Bubble Sort and Selection Sort Algorithms
* ============================================================
* Problem: WAP to implement from scratch:
* a) Bubble Sort (with early-exit optimization flag)
* b) Selection Sort
* ============================================================
*/
public class P30_BubbleSortAndSelectionSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean 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; // Optimization: already sorted!
}
}
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// Swap min with current element
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr1 = {64, 34, 25, 12, 22, 11, 90};
System.out.println("=== 1. BUBBLE SORT ===");
System.out.println("Before: " + Arrays.toString(arr1));
bubbleSort(arr1);
System.out.println("After : " + Arrays.toString(arr1));
int[] arr2 = {29, 10, 14, 37, 13};
System.out.println("\n=== 2. SELECTION SORT ===");
System.out.println("Before: " + Arrays.toString(arr2));
selectionSort(arr2);
System.out.println("After : " + Arrays.toString(arr2));
}
}