Level 2 | Algorithms | Lab 4
Selection Sort Algorithm
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting
the smallest (or largest) element from the unsorted portion of the list and moving it to the
sorted portion of the list.
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Selection Sort Algorithm:
Step 1: Set 𝑀𝑖𝑛 to position 0.
Step 2: Search for the smallest element in the unsorted subarray and update 𝑀𝑖𝑛.
Step 3: Swap the element at the position 𝑀𝑖𝑛 with the first element of the unsorted
subarray.
Step 4: Again set 𝑀𝑖𝑛 to the first position of the unsorted subarray
Step 5: Repeat steps 2 to 4 until the array gets sorted
1|Page
Modern Academy - Eng. Noha Ali
Level 2 | Algorithms | Lab 4
Selection Sort Code:
package selectionsort;
import [Link];
public class SelectionSort {
public static void Sort(int arr[])
{
int min;
for (int i=0 ; i<[Link]-1 ; i++)
{
min = i;
for (int j=i+1 ;j< [Link] ; j++)
{
if (arr[j] < arr[min])
min = j;
}
int temp = arr[min];
arr[min]= arr[i];
arr[i]=temp;
}
}
public static void main(String[] args) {
int arr_size;
Scanner s = new Scanner([Link]);
[Link]("Enter Array Size");
arr_size=[Link]();
int [] arr= new int[arr_size];
[Link]("Enter array Elements to be sorted!");
for (int i=0;i<[Link]; i++)
{
arr[i]=[Link]();
}
//int arr[]={7,4,5,9,8,2,1};
Sort(arr);
[Link]("Array After Sorting");
for (int i=0; i <[Link] ; i++)
[Link](arr[i]);
}
}
2|Page
Modern Academy - Eng. Noha Ali
Level 2 | Algorithms | Lab 4
Time Complexity for Selection Sort Algorithm ∈ 𝑶(𝒏𝟐 ).
3|Page
Modern Academy - Eng. Noha Ali