Selection Sort Algorithm
Selection sorting is like organizing a group of numbers from the smallest to the largest. It starts by finding the largest number in the group and putting it last index. Then, it looks for the next smallest number and puts it next to the first one. The algorithm keeps doing this until all the numbers are arranged in order from smallest to largest
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr= {-1,-99,-100,0};
selection(arr);
System.out.print(Arrays.toString(arr));
}
static void selection(int[]arr) {
for(int i=0;i<arr.length;i++) {
int last = arr.length-i-1;
int maxIndex = getMaxIndex(arr,0,last);
swap(arr,maxIndex,last);
}
}
private static int getMaxIndex(int[] arr, int start, int end) {
int max = start;
for(int i =start;i<=end;i++) {
if(arr[max]<arr[i]) {
max=i;
}
}
return max;
}
static void swap(int[] arr,int j, int k) {
int temp = arr[j];
arr[j] =arr[k];
arr[k]=temp;
}
}
getMaxIndex() function is used to get the index of the maximum element from the given array and the swap() function will help us to swap the element thus the resultant array is sorted
About the author
I am a Student who lives and breathe Software development.
Comments
Join the discussionNo comments yet. Be the first to comment.
