Skip to content

Commit ee6acf9

Browse files
authored
Create SelectionSort.java
1 parent 738f5a6 commit ee6acf9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Algorithms/Sorting/SelectionSort.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class SelectionSort
2+
{
3+
void sort(int arr[])
4+
{
5+
int n = arr.length;
6+
7+
// One by one move boundary of unsorted subarray
8+
for (int i = 0; i < n-1; i++)
9+
{
10+
// Find the minimum element in unsorted array
11+
int min_idx = i;
12+
for (int j = i+1; j < n; j++)
13+
if (arr[j] < arr[min_idx])
14+
min_idx = j;
15+
16+
// Swap the found minimum element with the first
17+
// element
18+
int temp = arr[min_idx];
19+
arr[min_idx] = arr[i];
20+
arr[i] = temp;
21+
}
22+
}
23+
24+
// Prints the array
25+
void printArray(int arr[])
26+
{
27+
int n = arr.length;
28+
for (int i=0; i<n; ++i)
29+
System.out.print(arr[i]+" ");
30+
System.out.println();
31+
}
32+
33+
// Driver code to test above
34+
public static void main(String args[])
35+
{
36+
SelectionSort ob = new SelectionSort();
37+
int arr[] = {64,25,12,22,11};
38+
ob.sort(arr);
39+
System.out.println("Sorted array");
40+
ob.printArray(arr);
41+
}
42+
}

0 commit comments

Comments
 (0)