]> Skullheadx's Git Forge - Sorting.git/commitdiff
Selection Sort added
authorSkullheadx <704277@pdsb.net>
Tue, 24 Jan 2023 23:28:58 +0000 (18:28 -0500)
committerSkullheadx <704277@pdsb.net>
Tue, 24 Jan 2023 23:28:58 +0000 (18:28 -0500)
sorting_algorithms/selection_sort.py

index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..cff5ee3fd1d1d1ca5d2f9e71442e22b6b6786a28 100644 (file)
@@ -0,0 +1,12 @@
+# Selection Sort (O(n^2))
+from utils import swap
+
+
+def selection_sort(array):
+    for index1 in range(len(array) - 1, -1, -1):  # loop through from end
+        swap_index = 0  # largest element to swap with
+        for index2 in range(index1 + 1):  # loop through the first index1 elements
+            if array[index2] > array[swap_index]:  # find the max element to swap with
+                swap_index = index2  # set the swap index
+        swap(array, index1, swap_index)  # use swap the largest and the index1 (from end)
+    return array  # return sorted array