Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

Worksheets related to Applied Discrete Structures

18156 views
ubuntu2004
Kernel: SageMath 10.4
def insertionSort(my_list): c=0 # for every element in our array for index in range(1, len(my_list)): current = my_list[index] position = index while position > 0 and my_list[position-1] > current: print("Swapped {} for {}".format(my_list[position], my_list[position-1])) my_list[position] = my_list[position-1] print(my_list) position -= 1 c+=index-position+1 my_list[position] = current return [my_list,c]
insertionSort([1,5,6,2,3,0,4])
Swapped 2 for 6 [1, 5, 6, 6, 3, 0, 4] Swapped 6 for 5 [1, 5, 5, 6, 3, 0, 4] Swapped 3 for 6 [1, 2, 5, 6, 6, 0, 4] Swapped 6 for 5 [1, 2, 5, 5, 6, 0, 4] Swapped 0 for 6 [1, 2, 3, 5, 6, 6, 4] Swapped 6 for 5 [1, 2, 3, 5, 5, 6, 4] Swapped 5 for 3 [1, 2, 3, 3, 5, 6, 4] Swapped 3 for 2 [1, 2, 2, 3, 5, 6, 4] Swapped 2 for 1 [1, 1, 2, 3, 5, 6, 4] Swapped 4 for 6 [0, 1, 2, 3, 5, 6, 6] Swapped 6 for 5 [0, 1, 2, 3, 5, 5, 6]
[[0, 1, 2, 3, 4, 5, 6], 17]
data=range(10)
j=4 k=7 data[:j-1]+data[k:k+1]+data[j:k]+data[k:]
[0, 1, 2, 7, 4, 5, 6, 7, 8, 9]
data[:0]
[]
def switch(data,i,j): h=data[i] data[i]=data[j] data[j]=h return data
switch(range(7),4,3)
[0, 1, 2, 4, 3, 5, 6]