Java Selection Sort Implementation

Selection sort is accomplished by using one level of nested loop. The outer loop goes through each array element until the second of the last element. Each of the outer loop current index position will get the next minimum value found from the inner loop. The inner loop starts from the next position of the outer loop’s current index position, then finds the minimum value from the rest of the unsorted array element and swap the position with the outer loop’s current position.

Here is an example of the selection sort in Java

public class SelectionSort {
	
	public static void selectionSort(int [] intArr)
	{
		int minIndex=0;
		int tempVal=0;
		
		//looping through the array till the second element from the end
		for(int i=0; i<intArr.length-1; i++)
		{
			//looping through the array starting from the next index to find the next minimum value 
			for(int j=i+1; j<intArr.length; j++)
			{
				if(intArr[j]<intArr[minIndex])
				{
					minIndex=j;//save the index of the minimum value
				}
			}
			
			//move the minimum value to the correct place
			tempVal=intArr[i];
			intArr[i]=intArr[minIndex];
			intArr[minIndex]=tempVal;
			System.out.print("During Sorting: ");
			printArr(intArr);
		}
		
		return;
	}
	
	public static void printArr(int[] arr)
	{
		for(int i=0; i<arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
		System.out.println();
	}
	
	public static void main(String args[])
	{
		int [] intArr={56,1,64,3,13,22};
		System.out.print("Before: ");
		printArr(intArr);
		SelectionSort.selectionSort(intArr);
		System.out.print("After: ");
		printArr(intArr);
	}

}

Output of the above selection sort java program:

Before: 56 1 64 3 13 22 
During Sorting: 1 56 64 3 13 22 
During Sorting: 1 3 64 56 13 22 
During Sorting: 1 3 13 56 64 22 
During Sorting: 1 3 13 22 64 56 
During Sorting: 1 3 13 22 56 64 
After: 1 3 13 22 56 64 

Search within Codexpedia

Custom Search

Search the entire web

Custom Search