From eb5bbcaa9c6626217cdcde70f3b05acebae1b91e Mon Sep 17 00:00:00 2001 From: Tanishk04 Date: Fri, 6 Oct 2023 14:24:52 +0530 Subject: [PATCH] added selection sort algorithm --- Sorting/selectionsort.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Sorting/selectionsort.py diff --git a/Sorting/selectionsort.py b/Sorting/selectionsort.py new file mode 100644 index 00000000..f3af4f94 --- /dev/null +++ b/Sorting/selectionsort.py @@ -0,0 +1,30 @@ +""" +Intuition is to pick smallest element every times loop proceeds +""" + +def selectionSort(arr): + """ + The selectionSort function implements the selection sort algorithm to sort an array in ascending + order. + + :param arr: The parameter `arr` is a list of elements that you want to sort using the selection sort + algorithm + + Time complexity: O(N^2), (where N = size of the array), for the best, worst, and average cases. + Space Complexity: O(1) + """ + n = len(arr) + + for i in range(0,n-1): + min_idx = i + for j in range(i,n): + if arr[j] < arr[min_idx]: + min_idx = j + # at this point we have collected information which element is smallest (between i and n-1)and its index is stored in min_idx + arr[i], arr[min_idx] = arr[min_idx], arr[i] + + +temp = input("Enter numbers separated by a comma:\n").strip() +arr = [int(item) for item in temp.split(",")] +selectionSort(arr) +print(arr) \ No newline at end of file