Data_structure) 6 sorting algorithms using python~!!
Hello everyone, I'm lulu.
Today I'm going to show you 6 sorting algorithms with time complexity and if it's stable or not.
First is bubble sort. This algorithm has O(n^2) time complexity and this algorithm is stable. However, I think O(n^2) time complexity regardless Best, Average, Worst case is not that great.
This is the source code of bubble_sort.
Second is insertion sort. This algorithm's Best case has O(n) time complexity but Average and Worst case has O(n^2) time complexity. Also it is stable.
This is the source code of insertion_sort.
Third is selection sort. This algorithm also has O(n^2) time complexity regardless Best, Average, Worst case. However, this algorithm is not stable.
This is the source code of selection_sort.
I'll post next 3 algorithms at next posting because it is too long to post 6 algorithms in one posting.
Today I'm going to show you 6 sorting algorithms with time complexity and if it's stable or not.
First is bubble sort. This algorithm has O(n^2) time complexity and this algorithm is stable. However, I think O(n^2) time complexity regardless Best, Average, Worst case is not that great.
def bubble_sort(data):
n = len(data)
for i in range(n - 1, 0, -1):
for j in range(0, i):
if data[j] > data[j + 1]:
data[j], data[j + 1] = data[j + 1], data[j]
return data
a=[2,5,4,1]
print(bubble_sort(a))
This is the source code of bubble_sort.
Second is insertion sort. This algorithm's Best case has O(n) time complexity but Average and Worst case has O(n^2) time complexity. Also it is stable.
def insertion_sort(data):
n = len(data)
for i in range(1, n):
val = data[i]
j = i
while j > 0 and data[j - 1] > val:
data[j] = data[j - 1]
j -= 1
data[j] = val
This is the source code of insertion_sort.
Third is selection sort. This algorithm also has O(n^2) time complexity regardless Best, Average, Worst case. However, this algorithm is not stable.
def selection_sort(data):
n = len(data)
for i in range(n):
smallest = data[i]
smallest_idx = i
for j in range(i, n):
if smallest > data[j]:
smallest = data[j]
smallest_idx = j
if i != smallest_idx:
data[i], data[smallest_idx] = data[smallest_idx], data[i]
This is the source code of selection_sort.
I'll post next 3 algorithms at next posting because it is too long to post 6 algorithms in one posting.
If you have any questions or any opinions, tell me you'll be welcomed :-)
Thank you :-)
Comments
Post a Comment