Created
July 28, 2018 09:34
-
-
Save beiweiqiang/f7ad527c38e3ee0b3a2092edf54382f6 to your computer and use it in GitHub Desktop.
merge sort AND bubble sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sorting | |
# Implement two types of sorting algorithms: | |
# Merge sort and bubble sort. | |
import math | |
from random import randint | |
def merge_arr(arr1, arr2): | |
""" | |
pass two sorted list, return merged sort | |
:param arr1: list | |
:param arr2: list | |
:return: list | |
""" | |
total_len = len(arr1) + len(arr2) | |
a = arr1[::] | |
b = arr2[::] | |
c = [] | |
a_index = 0 | |
b_index = 0 | |
a.append(math.inf) | |
b.append(math.inf) | |
while True: | |
if a[a_index] <= b[b_index]: | |
c.append(a[a_index]) | |
a_index += 1 | |
else: | |
c.append(b[b_index]) | |
b_index += 1 | |
if len(c) == total_len: | |
break | |
return c | |
def merge_sort(arr): | |
sort_arr = arr[::] | |
arr_len = len(sort_arr) | |
step = 1 | |
left_index = 0 | |
right_index = left_index + step | |
while True: | |
while True: | |
a = sort_arr[left_index:left_index + step] | |
right_end = right_index + step | |
if right_end >= arr_len: right_end = arr_len | |
b = sort_arr[right_index:right_end] | |
c = merge_arr(a, b) | |
sort_arr = sort_arr[0:left_index] + c + sort_arr[right_end:] | |
left_index = right_end | |
right_index = left_index + step | |
if right_end == arr_len: break | |
step *= 2 | |
left_index = 0 | |
right_index = left_index + step | |
if right_index >= arr_len: break | |
return sort_arr | |
def bubble_sort(arr): | |
sort_arr = arr[::] | |
for i in range(0, len(sort_arr) - 1): | |
for j in range(i + 1, len(sort_arr)): | |
if sort_arr[i] > sort_arr[j]: | |
sort_arr[i], sort_arr[j] = sort_arr[j], sort_arr[i] | |
return sort_arr | |
if __name__ == '__main__': | |
l = [] | |
for i in range(0, 100): | |
l.append(randint(0, 100)) | |
print(l) | |
print(merge_sort(l)) | |
print(bubble_sort(l)) | |
print(merge_arr([1, 4], [2, 3, 4, 9])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment