Selection Sort



Selection Sort
import java.util.Arrays;
public class SelectionSort{
    public static int[] selectionsort(int[] a){
        for(int i=0;i<a.length-1;i++){
            int minindex = i;
            int min = a[i];
            for(int j=i+1;j<=a.length-1;j++){
                if(min>a[j]){
                    minindex = j;
                    min = a[j];
                }
            }
            swap(a,i,minindex);
        }
        return a;
    }
    private static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i]=arr[j];
        arr[j] = temp;
        
    }
    public static void main(String[] args){
        int[] input = {2,2,435,33,3,3,3,56,6,6,7,8,3,6,9,8,6};
        
        System.out.println("Before: "+Arrays.toString(input));
        int[] output = selectionsort(input);        
        System.out.println("After: "+Arrays.toString(output));      
    }
}
/*
Before: [2, 2, 435, 33, 3, 3, 3, 56, 6, 6, 7, 8, 3, 6, 9, 8, 6]
After: [2, 2, 3, 3, 3, 3, 6, 6, 6, 6, 7, 8, 8, 9, 33, 56, 435]
*/


0 comments:

Post a Comment

Search This Blog

Powered by Blogger.