Why my sorting code doesn't working?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why my sorting code doesn't working??

import random class Sort: def sort(self, arr): pass def compare(self, item1, item2): if item1 < item2: return 1 elif item1 > item2: return -1 else: return 0 def swap(self, item1, item2): tmp = item1 item1 = item2 item2 = tmp def isSorted(self, arr): prev = 0 for i, j in zip(arr[:-1], arr[1:]): now = self.compare(i, j) if prev * now == -1: return False prev = now return True class BubbleSort(Sort): def sort(self, arr): n = len(arr) for i in range(n): for j in range(n-i-1): if arr[j] > arr[j+1]: self.swap(arr[j], arr[j+1]) arr=[] for i in range(10): arr.append(random.randint(0, 11)) print(arr) bubblesort = BubbleSort() bubblesort.sort(arr) print(arr)

21st Mar 2022, 7:26 AM
이지응
이지응 - avatar
3 Answers
+ 1
Your sort function no effect in that way, because its passing values , not by reference.. Either pass array and index values. Either use within sort function like for i in range(n): for j in range(n-1): if arr[j] > arr[j+1]: tmp = arr[j] arr[j] = arr[j+1] arr[j+1] = tmp Hope it helps...
21st Mar 2022, 8:49 AM
Jayakrishna 🇮🇳
+ 1
Isn't that python provides call-by-reference every time??
21st Mar 2022, 8:59 AM
이지응
이지응 - avatar
+ 1
Not every time. There you passing values only.. Instead try swap( arr, j, j+1) and see , also modify function defination accordingly.
21st Mar 2022, 9:02 AM
Jayakrishna 🇮🇳