From 77da85bf4c8278051e79257e7b413e7dac4e1672 Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Wed, 2 Mar 2016 14:06:15 -0800 Subject: [PATCH] code for chapter 2 --- 02_selection_sort/python/01_selection_sort.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 02_selection_sort/python/01_selection_sort.py diff --git a/02_selection_sort/python/01_selection_sort.py b/02_selection_sort/python/01_selection_sort.py new file mode 100644 index 0000000..4173eb5 --- /dev/null +++ b/02_selection_sort/python/01_selection_sort.py @@ -0,0 +1,22 @@ +# Finds the smallest value in an array +def findSmallest(arr): + # Stores the smallest value + smallest = arr[0] + # Stores the index of the smallest value + smallest_index = 0 + for i in range(1, len(arr)): + if arr[i] < smallest: + smallest = arr[i] + smallest_index = i + return smallest_index + +# Sort array +def selectionSort(arr): + newArr = [] + for i in range(len(arr)): + # Finds the smallest element in the array and adds it to the new array + smallest = findSmallest(arr) + newArr.append(arr.pop(smallest)) + return newArr + +print selectionSort([5, 3, 6, 2, 10])