Skip to content

Instantly share code, notes, and snippets.

@Mahedi-61
Created June 12, 2025 13:46
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(my_list):
for i in range(1, len(my_list)):
temp = my_list[i]
j = i -1
while j > -1:
if my_list[j] > temp:
my_list[j+1] = my_list[j]
my_list = 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(my_list, start_idx, end_idx):
pivot = start_idx
swap = pivot
for i in range(start_idx + 1, end_idx+1):
if my_list[i] < my_list[pivot]:
swap += 1
if swap != i:
my_list[i], my_list[swap] = my_list[swap], my_list[i]
my_list[swap], my_list[pivot] = my_list[pivot], my_list[swap]
return swap
def quick_sort_helper(my_list, left, right):
if left < right:
pivot = get_pivot(my_list, left, right)
quick_sort_helper(my_list, left, pivot-1)
quick_sort_helper(my_list, pivot+1, right)
return my_list
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