Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Selection Sort in Java

Selection Sort in Java

Selection Sort is a technique where a array is sequentially sorted by placing the smallest or the largest element from the array one after the other in multiple iterations. The time complexity of selection sort is more  then the time complexity of insertion sort. Algorithm is not suitable for large data sets.

Selection Sort in JAVA

Implementation

For implementation of Selection Sort we’ll have to follow the steps below

  • First we try to find the minimum element in the array and swap it with the element on the index 0.
  • Then, we move to the second position and find the smallest element in the array excluding index 0 and swap it with the element at index 1.
  • The above steps are then repeatedly followed until a sorted array is found.
Intro for Selection Sort in Java

Algorithm for selection sort in JAVA

  • sort(Arr[]):
  • l= Arr.length
  • FOR i from 1 to l-1:
  • min = i
  • FOR j = i+1 to l
  • if Arr[j]<Arr[min]
  • min = j
    swap(Arr[j], Arr[min])
  • END of FOR
  • END of FOR

Program for selection sort in JAVA

class PrepInsta 
{
// Main method, responsible for the execution of the code
public static void main(String args[])
{
PrepInsta ob = new PrepInsta();
int a[] = {19,17,25,43,15}; //initializing values to the array
ob.sort(a); //calling sort method
System.out.println("Sorted array");
ob.printArray(a); //calling printArray method
}

void sort(int a[])
{
int len = a.length; //calculating the length of the array
// One by one move boundary of unsorted subarray
for (int i = 0; i < len-1; i++)
{
// Find the minimum element in unsorted array
int min = i;
for (int j = i+1; j < len; j++)
if (a[j] < a[min])
min = j;

// Swap the found minimum element with the first element
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}

// Prints the sorted array
void printArray(int a[])
{
int len = a.length;
for (int i=0; i<len; ++i) //printing the sorted array
System.out.print(a[i]+" ");
System.out.println();
}


}

Highlights

  • Selection sort gives a time complexity of O(n2) in all cases regardless of arrangement of data
  • It could be useful in cases when swapping operation are very costly to do this would help as number of swaps in selection sort are :  size – 1
Selection sort in java meme