Home › Python programs (Hindi)
List को Sort करना Python में — bubble sort से sorted() तक
Problem statement
Numbers की list को ascending order में लगाना — पहले खुद sorting लिखकर (bubble sort), फिर Python के built-ins से।Approach 1: simple loop
Bubble sort: repeatedly walk the list, swapping any neighbouring pair that is out of order. Each full pass pushes the largest remaining value to the end, like a bubble rising.
nums = [5, 2, 9, 1]
for i in range(len(nums) - 1):
for j in range(len(nums) - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(nums)
# Output: [1, 2, 5, 9]The inner range shrinks by i because after pass 1 the last slot is already final, after pass 2 the last two are, and so on.
Approach 2: reusable function
Selection sort: find the smallest value in the unsorted part, swap it into place, repeat. Fewer swaps than bubble sort and just as easy to trace.
nums = [5, 2, 9, 1]
for i in range(len(nums) - 1):
smallest = i
for j in range(i + 1, len(nums)):
if nums[j] < nums[smallest]:
smallest = j
nums[i], nums[smallest] = nums[smallest], nums[i]
print(nums)
# Output: [1, 2, 5, 9]The outer loop fills position 0, then 1, then 2 — each with the smallest value not yet placed.
Approach 3: Pythonic alternative
Python's built-ins: sorted() returns a new sorted list, and .sort() sorts in place and returns None. Both accept a key and a reverse flag.
nums = [5, 2, 9, 1] print(sorted(nums)) # [1, 2, 5, 9] — original untouched print(sorted(nums, reverse=True)) # [9, 5, 2, 1] words = ["banana", "fig", "apple"] print(sorted(words, key=len)) # ['fig', 'apple', 'banana'] — by length nums.sort() # in place; nums itself changes print(nums) # [1, 2, 5, 9]
Exams ask for the hand-written loops; real code uses these — Timsort, the algorithm behind them, is heavily optimised and stable.
Dry run
[5, 2, 9, 1] पर bubble sort का pass 1 trace करें। जोड़ी (5, 2): अदला-बदली → [2, 5, 9, 1]। (5, 9): ठीक है, छोड़ो। (9, 1): अदला-बदली → [2, 5, 1, 9]। Pass 1 खत्म — 9 आखिरी slot में lock। Pass 2: [2, 1, 5, 9] — 5 lock। Pass 3: [1, 2, 5, 9]। हर pass में कम से कम एक slot final हो जाता है — इसीलिए inner range को छोटा करना safe है।Common errors
- Swap में tuple trick न लगाना —
a, b = b, aही सुरक्षित है। nums.sort()का result store करना — वहNonereturn करता है।- Inner loop की range में off-by-one —
nums[j + 1]list से बाहर जाएगा। - iवाला छोटा करना भूलना — काम चलेगा पर बेकार comparisons।- Mixed types sort करने की कोशिश — पहले एक type में convert करो।
Practice on PyDebug
Concept समझने के बाद इन free problems को browser में solve करें: