diff --git a/ALGORITHMS/Sorting/Bubble Sort/bubbleSort.py b/ALGORITHMS/Sorting/Bubble Sort/bubbleSort.py new file mode 100644 index 00000000..3fda407c --- /dev/null +++ b/ALGORITHMS/Sorting/Bubble Sort/bubbleSort.py @@ -0,0 +1,16 @@ +def bubbleSort(arr): + n = len(arr) + ctr = 0 + for i in range(n-1): + for j in range(0, n-i-1): + if arr[j] > arr[j + 1] : + arr[j], arr[j + 1] = arr[j + 1], arr[j] + ctr += 1 + print(ctr) + + +lst = [1, 2, 3, 5, 4] +bubbleSort(lst) +# since lists are mutable +# the main list itself changes +print(lst) \ No newline at end of file diff --git a/ALGORITHMS/Sorting/Bubble Sort/modifiedBubbleSort.py b/ALGORITHMS/Sorting/Bubble Sort/modifiedBubbleSort.py new file mode 100644 index 00000000..fb146ab1 --- /dev/null +++ b/ALGORITHMS/Sorting/Bubble Sort/modifiedBubbleSort.py @@ -0,0 +1,18 @@ +def bubbleSort(arr): + n = len(arr) + ctr = 0 + for i in range(n): + swapped = False + for j in range(0, n-i-1): + if arr[j] > arr[j+1] : + arr[j], arr[j+1] = arr[j+1], arr[j] + swapped = True + if swapped == False: + break + + +lst = [1, 2, 3, 5, 4] +bubbleSort(lst) +# since lists are mutable +# the main list itself changes +print(lst) \ No newline at end of file diff --git a/ALGORITHMS/Sorting/Insertion Sort/insertionSort.py b/ALGORITHMS/Sorting/Insertion Sort/insertionSort.py new file mode 100644 index 00000000..13a34b6a --- /dev/null +++ b/ALGORITHMS/Sorting/Insertion Sort/insertionSort.py @@ -0,0 +1,15 @@ +def insertionSort(arr): + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + while j >= 0 and key < arr[j] : + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key + + +lst = [1, 2, 3, 5, 4] +insertionSort(lst) +# since lists are mutable +# the main list itself changes +print(lst) \ No newline at end of file