-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSortExample.java
More file actions
55 lines (44 loc) · 1.52 KB
/
SelectionSortExample.java
File metadata and controls
55 lines (44 loc) · 1.52 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
import java.util.Scanner;
public class SelectionSortExample {
// Selection Sort method
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the current element is the minimum
// Find the minimum element in the unsorted part
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum with the first element of the unsorted part
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
// Method to display array
public static void displayArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numbers = new int[10];
// Read 10 numbers from the user
System.out.println("Enter 10 numbers:");
for (int i = 0; i < 10; i++) {
numbers[i] = sc.nextInt();
}
// Sort the array using Selection Sort
selectionSort(numbers);
// Display the sorted array
System.out.println("Sorted numbers:");
displayArray(numbers);
sc.close();
}
}