From a3fc9ef5290e8bfe007188b01657b5de36e51f93 Mon Sep 17 00:00:00 2001 From: Shubham Lad Date: Tue, 22 Oct 2019 16:38:08 +0530 Subject: [PATCH] added Selection Sort, Bubble Sort and Factorial to python Algoritm --- python/bubble_sort.py | 23 +++++++++++++++++++++++ python/factorial.py | 25 +++++++++++++++++++++++++ python/selection_sort.py | 25 +++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 python/bubble_sort.py create mode 100644 python/factorial.py create mode 100644 python/selection_sort.py diff --git a/python/bubble_sort.py b/python/bubble_sort.py new file mode 100644 index 0000000..a78657c --- /dev/null +++ b/python/bubble_sort.py @@ -0,0 +1,23 @@ +''' +Bubble Sort Algorithm + +https://en.wikipedia.org/wiki/Bubble_sort +''' + +def bubble_sort(arr): + length = len(arr) + + for i in range(length): + for j in range(1,length-i): + if arr[j-1] > arr[j]: + arr[j-1], arr[j] = arr[j], arr[j-1] + + +if __name__ == '__main__': + arr = [5, 10, 2, 0, 78, -2] + bubble_sort(arr) + print(arr) + +''' +output: [-2, 0, 2, 5, 10, 78] +''' \ No newline at end of file diff --git a/python/factorial.py b/python/factorial.py new file mode 100644 index 0000000..7ce70b9 --- /dev/null +++ b/python/factorial.py @@ -0,0 +1,25 @@ +''' +Program to calculate factorial of given number + +>>>factorial(1) +1 + +>>>factorial(10) +3628800 + +''' +def factorial(num): + if num < 0: + print("Enter positive number") + elif num == 0: + return 1 + else: + ans = 1 + for i in range(1, num+1): + ans *= i + + return ans + +if __name__ == '__main__': + num = int(input()) + print(factorial(num)) diff --git a/python/selection_sort.py b/python/selection_sort.py new file mode 100644 index 0000000..53ec516 --- /dev/null +++ b/python/selection_sort.py @@ -0,0 +1,25 @@ +''' +Selection sort algorithm implimented in Python +for more info on selection sort visit: +https://en.wikipedia.org/wiki/Selection_sort +''' + +def selection_sort(arr): + for i in range(len(arr)): + minimum = i + + for j in range(i+1, len(arr)): + if arr[j] < arr[minimum]: + minimum = j; + + if minimum != i: + arr[i], arr[minimum] = arr[minimum], arr[i] + +if __name__ == '__main__': + arr = [5, 10, 2, 0, 78, -2] + selection_sort(arr) + print(arr) + +''' +output: [-2, 0, 2, 5, 10, 78] +''' \ No newline at end of file