Difficulty: Easy
Topics: Sorting Algorithms, Iterative Methods
Companies: Commonly asked in technical interviews.
Selection sort is a sorting algorithm that iteratively selects the smallest element from the unsorted portion of the array and swaps it with the element at the beginning of the unsorted portion.
min_index
) of the unsorted portion of the array.min_index
to the current iterator value, assuming it is the smallest within the unsorted portion.min_index
, update min_index
to this element's index.min_index
is different from the current iterator in the outer loop, swap the elements at min_index
and the current iterator.Selection sort works by gradually building up a sorted portion of the array from left to right, ensuring that after each iteration of the outer loop, the left portion of the array is sorted correctly.
Selection sort operates with a time complexity of 𝑂(𝑛²), making it less efficient for large datasets compared to more advanced sorting algorithms like quicksort or mergesort.
[64, 25, 12, 22, 11]
11
) and swap it with the first element.[11, 25, 12, 22, 64]
12
) and swap it with the second element.[11, 12, 25, 22, 64]
22
) and swap it with the third element.[11, 12, 22, 25, 64]
[11, 12, 22, 25, 64]
Advantages:
Disadvantages:
Use selection sort for educational purposes or small datasets. For larger datasets, consider more efficient algorithms like quicksort or mergesort.
Loading component...
Loading component...
INPUT: int [] arr = {4,3,2,1};
OUTPUT: arr = {1,2,3,4}
public static void main(String[] args){
int[] arr = { 64, 25, 12, 22, 11 };
System.out.print("Original array: ");
printArray(arr);
selectionSort(arr, arr.length);
System.out.print("Sorted array: ");
printArray(arr);
} // Function End
static void selectionSort(int arr[], int n){
int i , j, min_idx;
for(i =0; i < n-1; i++){
min_idx = i;
for(j = i +1; j< n; j++){
if(arr[j] < arr[min_idx]){
min_idx = j;
}//If End
if(min_idx != i){
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}//If End
}//Loop End
}//Loop End
}//Function End
static void printArray(int[] arr){
for (int val : arr) {
System.out.print(val + " ");
}//Loop End
System.out.println();
} // Function End