Selection sort java

Hey guys!! Welcome to flower brackets blog. This post explains selection sort java.

selection sort java

In selection sort sorting algorithm smallest element in unsorted array is shifted to its correct position in an array.

The number of times sorting takes place will always be one less than the number of integer elements in an array.

Also read – insertion sort in java

To select lowest element we need to scan all “n” number of elements. Then comparing takes “n – 1” times and lastly swapping element to first position.

for comparisons, (n − 1) + (n − 2) + ... + 2 + 1 = n(n − 1) / 2

Here in this sorting algorithm we need two subarrays, first subarray for sorted array and second subarray for unsorted array.

In selection sort, loop continues until integer elements from unsorted subarray are arranged in the ascending order in sorted subarray . Let’s see java program for selection sort,

class SelectionSortJava 
{
void toSort(int arrNum[])
{
int number = arrNum.length;
for(int a = 0; a < number - 1; a++)
{
// finding minimum element
int minimum = a;
for(int b = a + 1; b < number; b++)
{
if(arrNum[b] < arrNum[minimum])
{
minimum = b;
}
}
// swapping minimum element with first element
int temp = arrNum[minimum];
arrNum[minimum] = arrNum[a];
arrNum[a] = temp;
}
}

// printing array
void displayArray(int arrPrint[])
{
int num = arrPrint.length;
for(int a = 0; a < num; ++a)
{
System.out.print(arrPrint[a] + " ");
}
System.out.println();
}

public static void main(String[] args)
{
SelectionSortJava obj = new SelectionSortJava();
int arrInput[] = {5,4,-3,2,-1};
obj.toSort(arrInput);
System.out.println("After sorting : ");
obj.displayArray(arrInput);
}
}

Output:

After sorting :
-3 -1 2 4 5

It is considered as one of the simplest algorithms. But not the fastest sorting algorithm. Because, outer “for loop” places the value to correct position while inner “for loop” finds next largest or smallest element.

Selection sort is useful for small data sets.

Time complexity : O(n²) because of outer and inner “for loops”.

Related Posts