Selection Sort Java

5:52 PM

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.(wikipedia)
 
import java.util.*;
public class SelectionSort {
    public static void main(String[] args){
         System.out.println("input array size");
        int n=input();
       
        int data[]=new int[n];
        System.out.println("input array value");
        for(int i=0;i<data.length;i++){
            data[i]=input();
        }
        urutkanSelection(data.length, data);
        System.out.print("hasil akhir : ");
        show(data.length,data);
    }
    public static void urutkanSelection(int n,int[] data){
        int posisi;
        for(int i=0;i<n-1;i++){
            posisi=i;
            for(int j=i+i;j<n;j++){
                if(data[posisi]>data[j]){
                    posisi=j;
                }}
                //Tukarkan
                int tmp=data[i];
                data[i]=data[posisi];
                data[posisi]=tmp;
                System.out.print("Hasil pada tahap ke-"+i+" :");
                show(n,data);
                System.out.println("");                                       
        }
       
    }
    static void show(int n,int[] data){
        for(int i=0;i<n;i++){
            System.out.print(data[i]+" ");
        }
       
    }
    static int input(){
        Scanner a=new Scanner(System.in);
        int b=a.nextInt();
        return b;
    }
}
 

You Might Also Like

0 comments