Selection Sort in Data Structure and Alogrithm

full-width Selection Sort in Data Structure and Alogrithm
Selection Sort


Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts;
Sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.

class khan{
	public static void main(String [] args){
		int i,j,mini_index,size,temp;
		int a[] = {12,13,67,10,5,4};      // Declare a Variable
		size = a.length;                 //Calculate Size of Array
		for(i = 0; i<size; i++){
			mini_index = i;
			for(j = i+1; j<size; j++){
				if(a[j] <a[mini_index]){
                    
                    //Swapping Values
					temp = a[j];
					a[j] = a[mini_index];
					a[mini_index] = temp;
					}
				}
			}

			for(i = 0; i  < size; i++){    //Print Selection Sorted Array
				System.out.println(a[i]);
				}
		}
	}

2nd Method
class hassan{
	public static void main(String [] args){
		int list[] = {2,12,10,15,20};
		int i,temp,j,size;     // Declare a Variable
		size = list.length;   //Calculate Size of Array

		for(i=0; i<size; i++){
		      for(j=i+1; j<size; j++){
		           if(list[i] > list[j])  
			   		{
                       //Swapping Values
		               temp=list[i];
		               list[i]=list[j];
		               list[j]=temp;
		            }
		       }
  		}
  		for(i=0; i<size; i++){
		  	System.out.println(list[i]);  //Print Selection Sorted Array
			}
	}
}

Advantages
  • Easy to write
  • Can be Done "in place "
  • Can be done on linked lists to (Keep a tail pointer)
Disadvantages
  • It is about N2 even in the best case for comparisons.
  • So the Running time (Over all inputs) is approximately O(N2).
  • The primary disadvantage of Selection sort is its poor efficiency when dealing with a huge list of items

إرسال تعليق

Post a Comment (0)

أحدث أقدم