Skip to content

Instantly share code, notes, and snippets.

@Mahedi-61
Last active July 6, 2025 16:58
Show Gist options
  • Save Mahedi-61/8cef75230e4ab3335ef85e2e216a4914 to your computer and use it in GitHub Desktop.
Save Mahedi-61/8cef75230e4ab3335ef85e2e216a4914 to your computer and use it in GitHub Desktop.
Practice code
def bubble_sort(my_list):
for i in range(len(my_list)-1, 0, -1): #steps
for j in range(0, i):
if my_list[j] > my_list[j+1]:
temp = my_list[j]
my_list[j] = my_list[j+1]
my_list[j+1] = temp
return my_list
def selection_sort(my_list):
for i in range(len(my_list) - 1):
min_index = i
for j in range(i+1, len(my_list)):
if (my_list[min_index] > my_list[j]):
min_index = j
if min_index != i:
temp = my_list[i]
my_list[i] = my_list[min_index]
my_list[min_index] = temp
return my_list
def insertion_sort(nums):
if len(nums) < 2: return
for i in range(1, len(nums)):
j = i - 1
if nums[i] < nums[j]:
while j >= 0 and nums[i] < nums[j]:
j -= 1
j += 1
temp = nums[i]
nums[j+1 : i+1] = nums[j : i]
nums[j] = temp
def insertion_sort(my_list):
for i in range(1, len(my_list)):
temp = my_list[i]
j = i -1
while j > -1 and my_list[j] > temp:
my_list[j+1] = my_list[j]
my_list[j] = temp
j -= 1
return my_list
def merge(list1, list2):
i = 0
j = 0
result = []
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
if i < len(list1):
result += list1[i:]
if j < len(list2):
result += list2[j:]
return result
def merge_sort(my_list):
if len(my_list) == 1 or len(my_list) == 0: return my_list
mid_index = len(my_list) // 2
left_list = merge_sort(my_list[ :mid_index])
right_list = merge_sort(my_list[mid_index: ])
return merge(left_list, right_list)
def quick_sort_using_mem(my_list):
if len(my_list) <= 1: return my_list
pivot = my_list[0]
left = [x for x in my_list[1:] if x <= pivot]
right = [x for x in my_list[1:] if x > pivot]
return quick_sort_using_mem(left) + [pivot] + quick_sort_using_mem(right)
def get_pivot(self, nums, start, end):
if len(nums) == 1: return 0
pivot = start
swap = start
for i in range(start + 1, end + 1):
if nums[i] < nums[pivot]:
swap += 1
if i != swap:
nums[i], nums[swap] = nums[swap], nums[i]
nums[pivot], nums[swap] = nums[swap], nums[pivot]
pivot = swap
return pivot
def quick_sort_helper(self, nums, start, end):
if start >= end:
return
pivot = self.get_pivot(nums, start, end)
self.quick_sort_helper(nums, start, pivot)
self.quick_sort_helper(nums, pivot+1, end)
def quick_sort(my_list):
return quick_sort_helper(my_list, 0, len(my_list)-1 )
my_list = [4,2,6,5,1,3]
#print(bubble_sort(my_list))
#print(selection_sort(my_list))
#print(insertion_sort(my_list))
#print(merge_sort(my_list))
print(quick_sort_using_mem(my_list))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment