From af4c10f5ea67361741ff35bee417678c27fe5116 Mon Sep 17 00:00:00 2001 From: Divya Agarwal <56511764+divya116@users.noreply.github.com> Date: Fri, 2 Oct 2020 13:43:08 +0530 Subject: [PATCH 1/2] Create heap_sort.py --- Algorithms/sorting/heap_sort.py | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Algorithms/sorting/heap_sort.py diff --git a/Algorithms/sorting/heap_sort.py b/Algorithms/sorting/heap_sort.py new file mode 100644 index 0000000..6645bad --- /dev/null +++ b/Algorithms/sorting/heap_sort.py @@ -0,0 +1,42 @@ +# To heapify subtree rooted at index i. +# n is size of heap +def heapify(arr, n, i): + largest = i # Initialize largest as root + l = 2 * i + 1 # left = 2*i + 1 + r = 2 * i + 2 # right = 2*i + 2 + + # See if left child of root exists and is + # greater than root + if l < n and arr[i] < arr[l]: + largest = l + + # See if right child of root exists and is + # greater than root + if r < n and arr[largest] < arr[r]: + largest = r + + # Change root, if needed + if largest != i: + arr[i],arr[largest] = arr[largest],arr[i] # swap + + # Heapify the root. + heapify(arr, n, largest) + +def heapSort(arr): + n = len(arr) + + # Build a maxheap - since last parent will be at ((n//2)-1) we can start at that location. + for i in range(n // 2 - 1, -1, -1): + heapify(arr, n, i) + + # One by one extract elements + for i in range(n-1, 0, -1): + arr[i], arr[0] = arr[0], arr[i] # swap + heapify(arr, i, 0) + +arr = [ 12, 11, 13, 5, 6, 7] +heapSort(arr) +n = len(arr) +print ("Sorted array is") +for i in range(n): + print ("%d" %arr[i]), From 4254756ac68d1ed87bdd8d8883b14d40f0465c8a Mon Sep 17 00:00:00 2001 From: Divya Agarwal <56511764+divya116@users.noreply.github.com> Date: Fri, 2 Oct 2020 13:44:58 +0530 Subject: [PATCH 2/2] Create selection_sort.py --- Algorithms/sorting/selection_sort.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Algorithms/sorting/selection_sort.py diff --git a/Algorithms/sorting/selection_sort.py b/Algorithms/sorting/selection_sort.py new file mode 100644 index 0000000..8542ef1 --- /dev/null +++ b/Algorithms/sorting/selection_sort.py @@ -0,0 +1,18 @@ +import sys +A = [100, 50, 200, 60, 40] + +# Traverse through all array elements +for i in range(len(A)): + + # Find the minimum element in remaining unsorted array + min_idx = i + for j in range(i+1, len(A)): + if A[min_idx] > A[j]: + min_idx = j + + # Swap the found minimum element with the first element + A[i], A[min_idx] = A[min_idx], A[i] + +print ("Sorted array") +for i in range(len(A)): + print("%d" %A[i]),