Skip to main content

Selection Sort in JAVA

What is selection sort?

It is a sorting technique that is based on the partitioning of array into two parts, sorted and unsorted.

The process is:-

1) Find minimum element in unsorted array.
2) Swap the element at the end of sorted array.

when i=0 we don't have any sorted array so element will be replaced from first element later the sorted array end will growas the index.


underline elements are sorted array, the length is increasing with each minimum element added at the end.

minimum element11
 11 25 12 22 64 
minimum element12
 11 12 25 22 64 
minimum element22
 11 12 22 25 64 
minimum element25
 11 12 22 25 64 
minimum element64
 11 12 22 25 64 


package sorting;

public class SelectionSort {

 //function to print array
  public static void print(int[] arr)
   for(int i=0;i<=arr.length-1;i++)
    System.out.print(" "+arr[i]);
   System.out.println(" ");
  //function to swap elements
  public static int[] swap(int[] arr,int i, int j)
   int temp;
   return arr;
  //program to find minimum element in unsorted array( i to end)
  public static int min(int[] arr,int i)
   int min=i;
   System.out.println("minimum element"+arr[min]);
   return min;
  public static void main(String[] args)
   int[] arr={64,25,12,22,11};
   int min;
   for(int i=0;i<=arr.length-1;i++)
    //find minimum element in unsorted array ( i to end)
    //swap minimum element with then end of sorted array(i)
    //print the array



Popular posts from this blog

Solved: The index 1 is out of range.

This error usually comes when we try to insert data in a query where there is no index defined for it. Example :- String strQuery=“select * from location where city_id=? ”; The question mark will be the the first index if we want to insert data so if we call a function like- oPreparedStatement = oConnection.prepareStatement(strQuery); oPreparedStatement.setString(1,235); here we are sending 235 as a first parameter so it will work fine but as soon as we write something after it like oPreparedStatement.setString(2,”kanpur”) then it will throw “The index 2 is out of range” since there is no place to send this value in a query hence it will throw the same error. Here index defines the parameter for which there is no place in the query. To rectify this we need to write query like- String strQuery=“select * from location where city_id=? And city_name=? ”; then it will work fine. The cases in which these errors can occur is- 1)Query is co

Best LeetCode Lists for Interviews

Here is a list of some of the best questions asked in interviews:- Must do 75 Must do 60 Must do medium:- Must do Easy:- Graph:-  Dynamic Programming:-  FaceBook interviews:-  Amazon Interviews:-  Google Interviews:-