33: Implement selection sort.
⏳⌚ 00:00:00

Question:-

Sort given array using selection sort.
Example 1:
Input:
N=6
arr[] = {3, 2, 9 , 1, 15, 10}
Output: {1, 2, 3, 9, 10, 15}
Example 2:
Input:
N=4
arr[] = {15. -2, 1, 18}
Output: {-2, 1, 15, 18}

Steps to solve:-

1. Function selectionsort:-The selectionsort function takes an integer array arr[] and its size n as parameters.
2. Outer Loop:- The outer loop iterates through the array from i = 0 to i = n-2 (inclusive). This loop selects the minimum element from the unsorted part of the array. Minimum Index: Inside the outer loop, a variable minIndex is initialized to i, representing the index of the current minimum element.
3. Inner Loop:- The inner loop runs from j = i+1 to j = n-1, searching for a smaller element in the unsorted part of the array. If an element at index j is smaller than the element at index minIndex, minIndex is updated to j.
4.Swap Elements::- After finding the minimum element in the unsorted part, a check is performed to see if minIndex is still equal to i. If not (meaning a smaller element was found), a swap operation is performed to move the minimum element to the current position i.
5.Main Function:- In the main function: The user inputs the number of elements n. An integer array arr of size n is declared to store the input elements. The user inputs the array elements. The selectionsort function is called to sort the array in ascending order. Finally, the sorted array is printed.

solution->

View Code 1
Time Complexity = O(n^2)
Space Complexity = O(n)