Sunday, March 24, 2024

BCA PART A 8. Implement Selection Sort

 



def selection_sort(arr):
    """
    Perform selection sort on the given list.
   
    Parameters:
        arr (list): The list to be sorted.
   
    Returns:
        list: Sorted list.
    """
    n = len(arr)
   
    for i in range(n-1):
        # Find the minimum element in the remaining unsorted list
        min_idx = i
        for j in range(i+1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
       
        # Swap the found minimum element with the first element
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
   
    return arr

# Accepting input from the user
arr = input("Enter elements of the list separated by space: ").split()
arr = [int(x) for x in arr]  # converting input strings to integers

# Sorting the input list using selection sort
sorted_arr = selection_sort(arr)

# Displaying the sorted list
print("Sorted array:", sorted_arr)


Output :

Enter elements of the list separated by space: 3 5 7 9 2 4 6 Sorted array: [2, 3, 4, 5, 6, 7, 9]



No comments:

Post a Comment