-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelection_sort.java
More file actions
80 lines (63 loc) · 1.95 KB
/
Copy pathSelection_sort.java
File metadata and controls
80 lines (63 loc) · 1.95 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
// public class Selection_sort {
// public static void main(String[] args) {
// int arr[] = {6,5,2,8,9,4};
// int size = arr.length;
// int temp =0;
// int minIndex = -1;
// for(int i=0;i<size-1;i++)
// minIndex = i;
// {
// for(int j=i+1;j<size;j++)
// {
// if(arr[minIndex] > arr[j] )
// {
// minIndex = j;
// }
// }
// temp = arr[minIndex];
// arr[minIndex] = arr[i];
// arr[i] = arr[temp];
// }
// System.out.println("Selection Sort: ");
// for(int num : arr)
// {
// System.out.print(num);
// }
// }
// }
public class Selection_sort {
// Function to perform selection sort
public static void selectionSort(int[] arr) {
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in the remaining unsorted array
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Function to print the array
public static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
// Main method
public static void main(String[] args) {
int[] numbers = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(numbers);
selectionSort(numbers);
System.out.println("Sorted array:");
printArray(numbers);
}
}