Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import time
- def generate_randonised_list(length):
- # generate a list containing 1000 values (0-999)
- rand_list = list()
- for x in range(length):
- rand_list.append(x)
- # randomly sort generated list
- random.shuffle(rand_list)
- return rand_list
- # source: https://www.geeksforgeeks.org/bubble-sort/
- def insertion_sort(arr):
- # Traverse through 1 to len(arr)
- for i in range(1, len(arr)):
- key = arr[i]
- # Move elements of arr[0..i-1], that are
- # greater than key, to one position ahead
- # of their current position
- j = i-1
- while j >= 0 and key < arr[j] :
- arr[j + 1] = arr[j]
- j -= 1
- arr[j + 1] = key
- return arr
- # source: https://www.geeksforgeeks.org/bubble-sort/
- def bubble_sort(arr):
- n = len(arr)
- # Traverse through all array elements
- for i in range(n):
- # Last i elements are already in place
- for j in range(0, n-i-1):
- # traverse the array from 0 to n-i-1
- # Swap if the element found is greater
- # than the next element
- if arr[j] > arr[j+1]:
- arr[j], arr[j+1] = arr[j+1], arr[j]
- return arr
- def main(list_length):
- randomised_list_1 = generate_randonised_list(list_length)
- randomised_list_2 = randomised_list_1.copy()
- start_time = time.time()
- insertion_sort(randomised_list_1)
- end_time = time.time()
- print('Insertion sort execution time:', end_time - start_time, 'seconds')
- start_time = time.time()
- bubble_sort(randomised_list_2)
- end_time = time.time()
- print('Bubble sort execution time:', end_time - start_time, 'seconds')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement