Friday, August 6, 2021

Java selection sort

Sorting an array using selection sort.
We first need to find minimum element in a array and swap with the first element.
Next step to pick the minimum element in the sub-array as first element will be the minimum hence the subarray will not include the first element.
Repeat the same process with this subarray as we did with the main array.

Suppose we have following array : { 23, 4, 1, 6, 7, 3, 4, 5 }

1.  Find minimum : 1 , swap with first element. array will be : { 1, 4, 23, 6, 7, 3, 4, 5 }
2.  First element is sorted hence take subarray {  4, 23, 6, 7, 3, 4, 5 } from main array { 1, 4, 23, 6, 7, 3,        4,  5 } without first element 
     repeat the above process : result will be { 1, 3, 23, 6, 7, 4, 4, 5}.
In this manner you will repeat the above process until all element sorted.
Worst case time complexity O(n^2)

Java code for the same is as follows :

public class SelectSort {
public static void main(String args[]) {
int[] arr = { 1, 2, 3, -4, 5, 6, -7, 8 ,0};
int min = 0;
int index = 0;
int temp = 0;
for (int j = 0; j <= arr.length - 1; j++) {
min = arr[j];
boolean swap = false;
for (int i = j+1; i <= arr.length - 1; i++) {
if (min > arr[i]) {
min = arr[i];
index = i;
swap = true;
}
}
if(swap) {
temp = arr[j];
arr[j] = min;
arr[index] = temp;
}
}
for (int k : arr) {
System.out.println(k);
}
}
}

Labels: , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home