Selection Sort Algorithm

The selection sort algorithm is an in-place comparison-based sorting algorithm. So basically the array can be divided into two parts: the unsorted part and the sorted part. Initially, the unsorted part contains the entire integer array and the sorted part is empty. We work with two loops here and we have a fixed (or pivot element) and a changing element from the array. The smallest element is pushed up or “selected” to move up to the pivot element.

image-courtesy: Google

Logic:
1. So we run two loops (let’s call the first loop as loop i and second loop as loop j)
2. Run loop i from 0 to length-1
3. Set a variable “small” to i. Let array[i] be called a pivot element.
4. Run loop j from i+1 to length and keep comparing all the elements to the pivot element
5. If array[j] happens to be lesser than pivot element then assign small to j
6. If small if not equal to i (it’s initial value) then swap pivot element and array[small];

Code:

View on/ Download from Github: (LINK). The code is in JAVA.


public class selection_sort {
	public static void main (String [] args){
		int array[]= {4,1,9,8,2,3};
		int length= array.length;
		
		for(int i=0; i<length-1; i++){
			int small=i;
			for(int j=i+1; j<length; j++){
				if(array[j]<array[small]){
					small=j;
				}
			}
			
			if(small!=i){
				int temp=array[i];
				array[i]=array[small];
				array[small]=temp;
			}
		}
		
		//display array
		for(int i=0;i<length; i++){
			System.out.println(array[i]);
		}
	}
}

HAPPY LEARNING!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: