Skip to content

Commit 9dd2e7e

Browse files
Merge pull request #156 from iamsunil25/selection
Selection sort in java
2 parents d34bb66 + fbc38d7 commit 9dd2e7e

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Sorting/selection_Sort.java

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

0 commit comments

Comments
 (0)