import java.util.Arrays; public class SelectionSort { public static void main(String[] args) { int arr[]={5,4,3,2,1}; insertion(arr); System.out.println(Arrays.toString(arr)); } static void insertion(int[] arr){ for(int i=0;i<=arr.length-2;i++){ for(int j=i+1;j>0;j--){ if(arr[j]<arr[j-1]){ swap(arr,j,j-1); } else{ break; } } } } static void selection(int[] arr){ for(int i=0;i<arr.length;i++){ //find the max item in the remaining array and swap with correct index int last=arr.length-i-1; int maxindex=getMaxIndex(arr,0,last); swap(arr,maxindex,last); } } static void swap(int[]arr,int first,int second){ int temp=arr[first]; arr[first]=arr[second]; arr[second]=temp; } static int getMaxIndex(int[] arr, int start, int end) { int max=start; for(int index=start;index<=end;index++){ if(arr[index]>arr[max]){ max=index; } } return max; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter