Skip to content

Instantly share code, notes, and snippets.

@jleonelpm
Created April 17, 2024 05:22
Show Gist options
  • Save jleonelpm/c545f08719992cef979f2a669fdc7f3f to your computer and use it in GitHub Desktop.
Save jleonelpm/c545f08719992cef979f2a669fdc7f3f to your computer and use it in GitHub Desktop.
Algorithm time execution
import time
import random
#selection sort algorithm with array argument
def selection_sort(arr):
start_time = time.perf_counter()
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
time_execution = time.perf_counter() - start_time
print(f"Selection Algorithm {time_execution} seconds")
#bubble sort algorithm with array argument
def bubble_sort(arr):
start_time = time.perf_counter()
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
time_execution = time.perf_counter() - start_time
print(f"Bubble Algorithm {time_execution} seconds")
#generate random array
arr = [random.randint(1, 1000) for i in range(100)]
#print(arr)
print(selection_sort(arr))
print(bubble_sort(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment