Skip to content

Commit d35bf75

Browse files
committed
Initial Commit
0 parents  commit d35bf75

26 files changed

+1141
-0
lines changed

Algorithms/BubbleSort.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def bubble_sort(arr):
2+
# Outer loop to iterate through the list n times
3+
for n in range(len(arr) - 1, 0, -1):
4+
# Inner loop to compare adjacent elements
5+
for i in range(n):
6+
if arr[i] > arr[i + 1]:
7+
# Swap elements if they are in the wrong order
8+
swapped = True
9+
arr[i], arr[i + 1] = arr[i + 1], arr[i]
10+
11+
# Sample list to be sorted
12+
arr = [39, 12, 18, 85, 72, 10, 2, 18]
13+
print("Unsorted list is:")
14+
print(arr)
15+
16+
bubble_sort(arr)
17+
18+
print("Sorted list is:")
19+
print(arr)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def binary_search(arr, x):
2+
low = 0
3+
high = len(arr) - 1
4+
mid = 0
5+
6+
while low <= high:
7+
8+
mid = (high + low) // 2
9+
10+
# If x is greater, ignore left half
11+
if arr[mid] < x:
12+
low = mid + 1
13+
14+
# If x is smaller, ignore right half
15+
elif arr[mid] > x:
16+
high = mid - 1
17+
18+
# means x is present at mid
19+
else:
20+
return mid
21+
22+
# If we reach here, then the element was not present
23+
return -1
24+
25+
26+
# Test array
27+
arr = [ 2, 3, 4, 10, 40 ]
28+
x = 10
29+
30+
# Function call
31+
result = binary_search(arr, x)
32+
33+
if result != -1:
34+
print("Element is present at index", str(result))
35+
else:
36+
print("Element is not present in array")
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def linear_search(arr, target):
2+
# Traverse through all elements in the array
3+
for index in range(len(arr)):
4+
# If the element is found, return its index
5+
if arr[index] == target:
6+
return index
7+
# If the element is not found, return -1
8+
return -1
9+
10+
# Example usage:
11+
arr = [10, 23, 45, 70, 11, 15]
12+
target = 70
13+
14+
# Function call
15+
result = linear_search(arr, target)
16+
17+
if result != -1:
18+
print(f"Element found at index: {result}")
19+
else:
20+
print("Element not found in the array")
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def linear_search_recursive(arr, target, index=0):
2+
# Base case: If index reaches the end of the list
3+
if index == len(arr):
4+
return -1 # Target not found
5+
6+
# If the target is found at the current index
7+
if arr[index] == target:
8+
return index # Return the index of the target
9+
10+
# Recursive call to check the next element
11+
return linear_search_recursive(arr, target, index + 1)
12+
13+
# Example usage
14+
arr = [10, 20, 30, 40, 50]
15+
target = 30
16+
17+
result = linear_search_recursive(arr, target)
18+
19+
if result != -1:
20+
print(f"Element {target} found at index {result}.")
21+
else:
22+
print(f"Element {target} not found in the list.")

Algorithms/MergeSort.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
def merge(arr, l, m, r):
2+
n1 = m - l + 1
3+
n2 = r - m
4+
5+
# create temp arrays
6+
L = [0] * (n1)
7+
R = [0] * (n2)
8+
9+
# Copy data to temp arrays L[] and R[]
10+
for i in range(0, n1):
11+
L[i] = arr[l + i]
12+
13+
for j in range(0, n2):
14+
R[j] = arr[m + 1 + j]
15+
16+
# Merge the temp arrays back into arr[l..r]
17+
i = 0 # Initial index of first subarray
18+
j = 0 # Initial index of second subarray
19+
k = l # Initial index of merged subarray
20+
21+
while i < n1 and j < n2:
22+
if L[i] <= R[j]:
23+
arr[k] = L[i]
24+
i += 1
25+
else:
26+
arr[k] = R[j]
27+
j += 1
28+
k += 1
29+
30+
# Copy the remaining elements of L[], if there are any
31+
while i < n1:
32+
arr[k] = L[i]
33+
i += 1
34+
k += 1
35+
36+
# Copy the remaining elements of R[], if there are any
37+
while j < n2:
38+
arr[k] = R[j]
39+
j += 1
40+
k += 1
41+
42+
# l is for left index and r is right index of the
43+
# sub-array of arr to be sorted
44+
45+
def mergeSort(arr, l, r):
46+
if l < r:
47+
48+
# Same as (l+r)//2, but avoids overflow for
49+
# large l and h
50+
m = l+(r-l)//2
51+
52+
# Sort first and second halves
53+
mergeSort(arr, l, m)
54+
mergeSort(arr, m+1, r)
55+
merge(arr, l, m, r)
56+
57+
58+
# Driver code to test above
59+
arr = [12, 11, 13, 5, 6, 7]
60+
n = len(arr)
61+
print("Given array is")
62+
for i in range(n):
63+
print("%d" % arr[i],end=" ")
64+
65+
mergeSort(arr, 0, n-1)
66+
print("\n\nSorted array is")
67+
for i in range(n):
68+
print("%d" % arr[i],end=" ")

Algorithms/QuickSort.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
def partition(array, low, high):
2+
# choose the rightmost element as pivot
3+
pivot = array[high]
4+
5+
# pointer for greater element
6+
i = low - 1
7+
8+
# traverse through all elements compare each element with pivot
9+
for j in range(low, high):
10+
if array[j] <= pivot:
11+
12+
# If element smaller than pivot is found swap it with the greater element pointed by i
13+
i = i + 1
14+
15+
# Swapping element at i with element at j
16+
(array[i], array[j]) = (array[j], array[i])
17+
18+
# Swap the pivot element with the greater element specified by i
19+
(array[i + 1], array[high]) = (array[high], array[i + 1])
20+
21+
# Return the position from where partition is done
22+
return i + 1
23+
24+
def quickSort(array, low, high):
25+
if low < high:
26+
# Find pivot element such that element smaller than pivot are on the left element greater than pivot are on the right
27+
pi = partition(array, low, high)
28+
29+
# Recursive call on the left of pivot
30+
quickSort(array, low, pi - 1)
31+
32+
# Recursive call on the right of pivot
33+
quickSort(array, pi + 1, high)
34+
35+
data = [1, 7, 4, 1, 10, 9, -2]
36+
print("Unsorted Array")
37+
print(data)
38+
39+
size = len(data)
40+
41+
quickSort(data, 0, size - 1)
42+
43+
print('Sorted Array in Ascending Order:')
44+
print(data)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def binary_search(arr, low, high, x):
2+
# Check base case
3+
if high >= low:
4+
5+
mid = (high + low) // 2
6+
7+
# If element is present at the middle itself
8+
if arr[mid] == x:
9+
return mid
10+
11+
# If element is smaller than mid, then it can only
12+
# be present in left subarray
13+
elif arr[mid] > x:
14+
return binary_search(arr, low, mid - 1, x)
15+
16+
# Else the element can only be present in right subarray
17+
else:
18+
return binary_search(arr, mid + 1, high, x)
19+
20+
else:
21+
# Element is not present in the array
22+
return -1
23+
24+
# Test array
25+
arr = [ 2, 3, 4, 10, 40 ]
26+
x = 10
27+
28+
# Function call
29+
result = binary_search(arr, 0, len(arr)-1, x)
30+
31+
if result != -1:
32+
print("Element is present at index", str(result))
33+
else:
34+
print("Element is not present in array")

Algorithms/SelectionSort.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def selectionSort(array, size):
2+
for ind in range(size):
3+
min_index = ind
4+
5+
for j in range(ind + 1, size):
6+
# select the minimum element in every iteration
7+
if array[j] < array[min_index]:
8+
min_index = j
9+
# swapping the elements to sort the array
10+
(array[ind], array[min_index]) = (array[min_index], array[ind])
11+
12+
arr = [-2, 45, 0, 11, -9,88,-97,-202,747]
13+
size = len(arr)
14+
selectionSort(arr, size)
15+
print('The array after sorting in Ascending Order by selection sort is:')
16+
print(arr)
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
class Tree:
2+
def __init__(self, val=None) -> None:
3+
self.value = val
4+
5+
if self.value:
6+
self.left = Tree()
7+
self.right = Tree()
8+
else:
9+
self.left = None
10+
self.right = None
11+
12+
def isEmpty(self):
13+
return (self.value == None)
14+
15+
def isleaf(self):
16+
# Check if the tree node is a leaf node (both left and right children are None)
17+
if self.left.left == None and self.right.right == None:
18+
return True
19+
else:
20+
return False
21+
22+
def insert(self, data):
23+
if self.isempty():
24+
# If the current node is empty, insert the data as its value
25+
self.value = data
26+
# Create empty left and right children
27+
self.left = Tree()
28+
self.right = Tree()
29+
elif self.value == data:
30+
# If the data already exists in the tree, return
31+
return
32+
elif data < self.value:
33+
# If the data is less than the current node's value, insert it into the left subtree
34+
self.left.insert(data)
35+
return
36+
elif data > self.value:
37+
# If the data is greater than the current node's value, insert it into the right subtree
38+
self.right.insert(data)
39+
return
40+
41+
def find(self, v):
42+
if self.isEmpty():
43+
print("{} is not found".format(v))
44+
return False
45+
if self.value == v:
46+
print("{} is found".format(v))
47+
return True
48+
if v < self.value:
49+
return self.left.find(v)
50+
else:
51+
return self.right.find(v)
52+
53+
def inorder(self):
54+
if self.isempty():
55+
# If the tree is empty, return an empty list
56+
return []
57+
else:
58+
# Return the inorder traversal of the tree (left subtree, root, right subtree)
59+
return self.left.inorder() + [self.value] + self.right.inorder()
60+
61+
def maxval(self):
62+
# Find the maximum value in the Tree
63+
if self.right.right == None:
64+
return (self.value)
65+
else:
66+
return (self.right.maxval())
67+
68+
def delete(self, v):
69+
# Delete a value from the Tree
70+
if self.isempty():
71+
return
72+
if v < self.value:
73+
self.left.delete(v)
74+
return
75+
if v > self.value:
76+
self.right.delete(v)
77+
return
78+
if v == self.value:
79+
if self.isleaf():
80+
self.value = None
81+
self.left = None
82+
self.right = None
83+
return
84+
elif self.left.isempty():
85+
self.value = self.right.value
86+
self.left = self.right.left
87+
self.right = self.right.right
88+
return
89+
else:
90+
self.value = self.left.maxval()
91+
self.left.delete(self.left.maxval())
92+
return
93+
94+
# Test the Tree class
95+
t = Tree(15)
96+
t.insert(10)
97+
t.insert(18)
98+
t.insert(4)
99+
t.insert(11)
100+
t.insert(16)
101+
t.insert(20)
102+
print("Before deleting 4: ")
103+
print(t.inorder())
104+
t.delete(4)
105+
print("After deleting 4: ")
106+
print(t.inorder())

0 commit comments

Comments
 (0)