Selection Sort


  • Time Complexity - O(n^2)  || Space Complexity - O(1)
  • In selection sort, we divide an array into two parts - sorted and unsorted (by i loop here in code)
  • We find the minimum element's index from the unsorted array (here by j loop) and swap



public class Main {
    public static void main(String[] args) throws Exception {
        int[] arr={1,4,4,5,6,2,3,90,120,43,0};
       
        System.out.println("UnSorted Array :");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println();
        // selection sort
        for(int i=0;i<arr.length;i++){
           
            int minIndex=i;
            // find minimum from unsorted array
            for(int j=i+1;j<arr.length;j++){
                if(arr[minIndex]>arr[j]){
                    minIndex=j;
                }
            }
            // now as we got index of minimum element from unsorted array in minIndex, we first see if our earlier minIndex
            //that is i is same after the finding the minIndex through loop of j
           
            // if it is same we do not need to swap
            // if it is different , we swap
           
            if(i!=minIndex){
                int temp = arr[i];
                arr[i]=arr[minIndex];
                arr[minIndex]=temp;
            }
        }
       
       
        System.out.println();
        System.out.println("Sorted Array in non decreasing order:");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}


Output:

UnSorted Array :
1 4 4 5 6 2 3 90 120 43 0 

Sorted Array in increasing order:
0 1 2 3 4 4 5 6 43 90 120 

Comments

Popular posts from this blog

Binary Heap - Introduction

Divide and Conquer - Introduction

Bubble Sort