Bubble Sort

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

dsa

June 4, 2024

1 Bubble Sort
[2]: def bubble_sort(elements):
length = len(elements)

for i in range(length-1):
sorted = False
for j in range(length-1-i):
if elements[j] > elements[j+1]:
temp = elements[j]
elements[j] = elements[j+1]
elements[j+1] = temp

sorted = True

if not sorted:
break

[3]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]


bubble_sort(elements)

[4]: elements

[4]: [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

1.1 Excercise
[42]: def bubble_sort_dict(elements, key='transaction_amount'):
length = len(elements)

for i in range(length):
for j in range(length-1):
if elements[j][key] > elements[j+1][key]:
elements[j], elements[j+1] = elements[j+1], elements[j]

1
[43]: elements = [
{ 'name': 'mona', 'transaction_amount': 1000, 'device': 'iphone-10'},
{ 'name': 'dhaval', 'transaction_amount': 400, 'device': 'google␣
↪pixel'},

{ 'name': 'kathy', 'transaction_amount': 200, 'device': 'vivo'},


{ 'name': 'aamir', 'transaction_amount': 800, 'device': 'iphone-8'},
]

[50]: bubble_sort_dict(elements, key='name')

[51]: elements

[51]: [{'name': 'aamir', 'transaction_amount': 800, 'device': 'iphone-8'},


{'name': 'dhaval', 'transaction_amount': 400, 'device': 'google pixel'},
{'name': 'kathy', 'transaction_amount': 200, 'device': 'vivo'},
{'name': 'mona', 'transaction_amount': 1000, 'device': 'iphone-10'}]

2 Selection Sort
[19]: def selection_sort(elements):

length = len(elements)

for i in range(length):
min_index = i
for j in range(i+1, length):
if elements[j] < elements[min_index]:
min_index = j

if min_index != i :
elements[i], elements[min_index] = elements[min_index], elements[i]

[20]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]


selection_sort(elements)

[21]: elements

[21]: [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

2.1 Exercise
[ ]:

[71]: def selection_sort_dict(details, sort_by_list):

2
length = len(details)

for sort_by in sort_by_list[::-1]:


for i in range(length):
min_index = i
for j in range(i+1, length):
if details[min_index][sort_by] > details[j][sort_by]:
min_index = j

if min_index != i:
details[i], details[min_index] = details[min_index], details[i]

[72]: student_list = [
{'First Name': 'Raj', 'Last Name': 'Nayyar'},
{'First Name': 'Suraj', 'Last Name': 'Sharma'},
{'First Name': 'Karan', 'Last Name': 'Kumar'},
{'First Name': 'Jade', 'Last Name': 'Canary'},
{'First Name': 'Raj', 'Last Name': 'Thakur'},
{'First Name': 'Raj', 'Last Name': 'Sharma'},
{'First Name': 'Kiran', 'Last Name': 'Kamla'},
{'First Name': 'Armaan', 'Last Name': 'Kumar'},
{'First Name': 'Jaya', 'Last Name': 'Sharma'},
{'First Name': 'Ingrid', 'Last Name': 'Galore'},
{'First Name': 'Jaya', 'Last Name': 'Seth'},
{'First Name': 'Armaan', 'Last Name': 'Dadra'},
{'First Name': 'Ingrid', 'Last Name': 'Maverick'},
{'First Name': 'Aahana', 'Last Name': 'Arora'}
]

sort_by_list = ['First Name', 'Last Name']

selection_sort_dict(student_list, sort_by_list)

[73]: student_list

[73]: [{'First Name': 'Aahana', 'Last Name': 'Arora'},


{'First Name': 'Armaan', 'Last Name': 'Dadra'},
{'First Name': 'Armaan', 'Last Name': 'Kumar'},
{'First Name': 'Ingrid', 'Last Name': 'Galore'},
{'First Name': 'Ingrid', 'Last Name': 'Maverick'},
{'First Name': 'Jade', 'Last Name': 'Canary'},
{'First Name': 'Jaya', 'Last Name': 'Seth'},
{'First Name': 'Jaya', 'Last Name': 'Sharma'},
{'First Name': 'Karan', 'Last Name': 'Kumar'},
{'First Name': 'Kiran', 'Last Name': 'Kamla'},
{'First Name': 'Raj', 'Last Name': 'Sharma'},
{'First Name': 'Raj', 'Last Name': 'Nayyar'},

3
{'First Name': 'Raj', 'Last Name': 'Thakur'},
{'First Name': 'Suraj', 'Last Name': 'Sharma'}]

3 Insertion Sort
[118]: def insertion_sort(elements):

for i in range(1, len(elements)):

key = elements[i]

j = i - 1

while j>=0 and key < elements[j]:


elements[j+1] = elements[j]

j -= 1
elements[j+1] = key

[119]: 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

[124]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]

[125]: insertion_sort(elements)

[126]: elements

[126]: [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

[ ]:

4
4 Merge Sort
[236]: def merge_sort(elements):

length = len(elements)

if length <= 1:
return elements

mid = length//2

left = elements[:mid]
right = elements[mid:]

merge_sort(left)
merge_sort(right)

i = j = k = 0

while i < len(left) and j < len(right):


if left[i] <= right[j]:
elements[k] = left[i]
i += 1
else:
elements[k] = right[j]
j += 1

k += 1

while i < len(left):


elements[k] = left[i]
i += 1
k += 1
while j < len(right):
elements[k] = right[j]
j += 1
k += 1

[237]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]

[238]: merge_sort(elements)

[239]: elements

[239]: [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

5
4.1 Excercise
[198]: def merge_sort_dict(elements, key='name'):

length = len(elements)

if length <= 1:
return elements

mid = length // 2

left = elements[:mid]
right = elements[mid:]

left = merge_sort_dict(left)
right = merge_sort_dict(right)

i = j = 0

sorted_list = []

while i < len(left) and j < len(right):


if left[i][key] <= right[j][key]:
# elements[k] = elements[i]
sorted_list.append(left[i])
i += 1
else:
# elements[k] = elements[j]
sorted_list.append(left[j])
j += 1

# k += 1

while i < len(left):


# elements[k] = elements[i]
sorted_list.append(left[i])
i += 1
# k += 1

while j < len(right):


# elements[k] = elements[j]
sorted_list.append(left[j])
j += 1
# k += 1

return sorted_list

6
[232]: def merge_sort_ex(elements, key='name'):

length = len(elements)

if length <= 1:
return

mid = length // 2

left = elements[:mid]
right = elements[mid:]

merge_sort_ex(left)
merge_sort_ex(right)

sorted_list = []

i = j = 0

while i < len(left) and j < len(right):


if left[i][key] <= right[j][key]:
sorted_list.append(left[i])
i += 1
else:
sorted_list.append(right[j])
j += 1

sorted_list.extend(left[i:])
sorted_list.extend(left[j:])

return sorted_list

[233]: elements = [
{ 'name': 'vedanth', 'age': 17, 'time_hours': 1},
{ 'name': 'rajab', 'age': 12, 'time_hours': 3},
{ 'name': 'vignesh', 'age': 21, 'time_hours': 2.5},
{ 'name': 'chinmay', 'age': 24, 'time_hours': 1.5},
]

[234]: mid = len(elements) // 2


elements[:mid]

[234]: [{'name': 'vedanth', 'age': 17, 'time_hours': 1},


{'name': 'rajab', 'age': 12, 'time_hours': 3}]

[235]: merge_sort_ex(elements)

7
[235]: [{'name': 'vedanth', 'age': 17, 'time_hours': 1},
{'name': 'rajab', 'age': 12, 'time_hours': 3},
{'name': 'vedanth', 'age': 17, 'time_hours': 1},
{'name': 'rajab', 'age': 12, 'time_hours': 3}]

[ ]:

5 Quick sort
[ ]:

[24]: def quick_sort(elements):


length = len(elements)

if length <= 1:
return elements
else:
pivot = elements.pop()

lower_element = []
higher_element = []

for i in elements:
if i < pivot:
lower_element.append(i)
else:
higher_element.append(i)

return quick_sort(lower_element) + [pivot] + quick_sort(higher_element)

[25]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]

[35]: quick_sort(elements)

[35]: [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

[ ]:

[ ]:

8
6 Linear Search algorithm
[30]: def linear_search(elements, n):

for i in range(len(elements)):
if elements[i] == n:
return f'Found at {i}th position'
else:
return f'{n} Not Found'
break

[31]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]

linear_search(elements , 100)

[31]: '100 Not Found'

7 Binary Search algorithm


[26]: def binary_search(elements, target):

length = len(elements)

if length <= 1:
return elements

left, right = 0, length - 1

while left <= right:

mid = (left + right) // 2

if elements[mid] == target:
return f"{target} found at {mid}th postion"

elif target < elements[mid]:


right = mid -1
else:
left = mid + 1

if right <= left:


return 'element not found'

[27]: elements = [1,75,2,5,73,12,43,17,23,79,102,90, 47,57,45]

sorted_elements = quick_sort(elements)

9
[62]: binary_search(sorted_elements,10)

[62]: 'element not found'

8 Jump Search algorithm


[11]: def jump_search(arr, target):
n = len(arr)
step = int(n**0.5)
prev = 0

while arr[min(step, n)-1] < target:

prev = step
step += int(n**0.5)
if prev >= n:
return -1

for i in range(prev, min(step, n)):


if arr[i] == target:
return f'{target} found at {i} position'

return -1

[13]: elements = [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]
jump_search(elements, 6)

[13]: -1

9 Interpolation Search
[18]: def interpolation_search(arr, target):
low = 0
high = len(arr) - 1

while low <= high and target >= arr[low] and target <= arr[high]:
if low == high:
if arr[low] == target:
return low
return 'target not found'

pos = low + ((target - arr[low]) * (high - low) // (arr[high] -␣


↪arr[low]))

if arr[pos] == target:

10
return pos

if arr[pos] < target:


low = pos + 1
else:
high = pos - 1

return 'target not found'

[20]: elements = [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

interpolation_search(elements, 49)

[20]: 'target not found'

10 Exponential Search
[28]: def exponential_search(arr, target):

if arr[0] == target:
return 0

i = 1
while i < len(arr) and arr[i] <= target:
i *= 2

return binary_search(arr, target)

[30]: elements = [1, 2, 5, 12, 17, 23, 43, 45, 47, 57, 73, 75, 79, 90, 102]

exponential_search(elements, 0)

[30]: 'element not found'

11

You might also like