-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sorting
50 lines (45 loc) · 1.49 KB
/
Sorting
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
import java.util.*;
public class SortingExample {
public static void main(String[] args) {
// Bubble Sort
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("Bubble Sorted Array: " + Arrays.toString(arr));
// Selection Sort
int[] arr2 = {64, 34, 25, 12, 22, 11, 90};
selectionSort(arr2);
System.out.println("Selection Sorted Array: " + Arrays.toString(arr2));
// Using Collections.sort()
List<Integer> numbers = new ArrayList<>(Arrays.asList(64, 34, 25, 12, 22, 11, 90));
Collections.sort(numbers);
System.out.println("Sorted List: " + numbers);
}
// Bubble Sort
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
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;
}
}
}
}
// 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;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}