Reputation: 27
I am working on a program to compare ways of sorting. I am using the comparisons made to track the efficiency of each program. I have been able to track how many comparisons are made, but i cannot get the comparisons from the function back into the original variable.
import random
# allows user to create a set of numbers, at their desiered length
setSize = int(input('How many numbers are we sorting today?'))
# creates a random list of numbers between 0 and 999,999
numbers = random.sample(range(0, 999999), setSize)
SelectionCount = 0
def sort (arr, a, b, i, j, count):
while j < a:
while i < a:
if arr[b] > arr[i]:
b = i
count += 1
i += 1
arr[j], arr[b] = arr[b], arr[j]
j += 1
i = j
b = i
sort(numbers, setSize, 0, 0, 0, SelectionCount)
print("The sort has been completed, there were " + str(SelectionCount) + " comparisons made!")
Upvotes: 2
Views: 41
Reputation: 195438
You can return the count from the function. Also, you don't have to put a, b, i, j
as function parameters, just initialize them inside the function.
For example:
import random
# allows user to create a set of numbers, at their desiered length
setSize = int(input('How many numbers are we sorting today?'))
# creates a random list of numbers between 0 and 999,999
numbers = random.sample(range(0, 999999), setSize)
def sort (arr):
a, b = len(arr), 0
i, j = 0, 0
count = 0
while j < a:
while i < a:
if arr[b] > arr[i]:
b = i
count += 1
i += 1
arr[j], arr[b] = arr[b], arr[j]
j += 1
i = j
b = i
return count
SelectionCount = sort(numbers)
print("The sort has been completed, there were " + str(SelectionCount) + " comparisons made!")
Prints:
How many numbers are we sorting today?10
The sort has been completed, there were 12 comparisons made!
Upvotes: 2