Skip to content

Instantly share code, notes, and snippets.

@Delation
Last active April 10, 2024 16:37
Show Gist options
  • Save Delation/0b1a821d4921fa7ba058bf0040d57c19 to your computer and use it in GitHub Desktop.
Save Delation/0b1a821d4921fa7ba058bf0040d57c19 to your computer and use it in GitHub Desktop.
Practice sorting lists for my Computer Science class
import random, time
### Test case functions
# Check for sorted list
def is_sorted(a:list) -> bool:
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
return False
return True
# Test if sort function works
def test_sort(func:callable, size:int, max_size:int) -> None:
print('Testing sort %s()...' % func.__name__)
test_list = []
for i in range(size):
test_list.append(random.randint(0, max_size))
#print('Random list generated:\n%s' % test_list)
test_start = time.time()
func(test_list)
print('Sort took %s seconds.' % (time.time() - test_start))
#print('List after sort:\n%s' % test_list)
print('%s %s.' % (func.__name__, 'works' if is_sorted(test_list) else 'does NOT work'))
### Sort functions
def swap(a:list, i:int, j:int) -> None:
a[i], a[j] = a[j], a[i]
# Merge sort
def merge_sort(a:list) -> None:
b = a[:len(a)//2]
c = a[len(a)//2:] # when a is odd, always bigger
if len(b) > 1:
merge_sort(b)
merge_sort(c)
elif len(c) > 1:
merge_sort(c)
a.clear()
while len(b) > 0 or len(c) > 0:
if len(b) == 0:
a.append(c.pop(0))
elif len(c) == 0:
a.append(b.pop(0))
else:
if b[0] > c[0]:
a.append(c.pop(0))
else:
a.append(b.pop(0))
def bubble_sort(a:list) -> None:
for i in range(len(a)):
for j in range(len(a) - i - 1):
if a[j] > a[j + 1]:
swap(a, j + 1, j)
### Python functions
def main() -> None:
size = int(input('What size?\n> '))
max_size = int(input('Max int size?\n> '))
# Test cases
test_sort(merge_sort, size, max_size)
test_sort(bubble_sort, size, max_size)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment