Compare each pair of neighbors, swap the ones out of order, and let the largest values drift to the end โ one pass at a time.
โ Back to the Field GuideHar bir qo'shni juftlikni solishtiring, tartibsizlarini swap qiling โ shunda eng katta qiymatlar pass sayin qatorning oxiriga suzib boradi.
โ Qo'llanmaga qaytishWatch the bars below: each pass walks left to right, swapping any two neighbors that are out of order. The largest remaining value always "bubbles" to the end of the unsorted range โ do enough passes and the whole row settles into order, one simple local swap at a time.
Quyidagi ustunlarga qarang: har bir pass chapdan o'ngga yurib, tartibsiz turgan har qanday qo'shni juftlikni almashtiradi. Qolgan eng katta qiymat doim tartiblanmagan qismning oxiriga "suzib" boradi โ yetarlicha pass qilinsa, butun qator tartiblanadi, har safar bitta oddiy, mahalliy almashtirish orqali.
arr[0] and arr[1].arr[0] va arr[1] ni, solishtiring.Time: O(nยฒ) in the average and worst case. For roughly every one of the n elements, a pass may need to compare across almost the full remaining range to bubble the right value into place โ about n passes of up to n comparisons each multiply out to nยฒ work. With the early-exit check in place, the best case (an already-sorted array) drops to O(n): one pass confirms nothing needs swapping, and the algorithm stops immediately.
Space: O(1). Bubble sort rearranges elements inside the same array using a single temporary swap โ it never allocates a second array or any structure that grows with the input, so its memory footprint stays constant no matter how large the array is.
Vaqt: O(nยฒ) โ o'rtacha va eng yomon holatda. Taxminan n ta elementning har biri uchun, to'g'ri qiymatni joyiga suzdirish uchun qolgan qismning deyarli hammasini solishtirish kerak bo'lishi mumkin โ har biri n tagacha solishtirishdan iborat bo'lgan taxminan n ta pass ko'paytirilganda nยฒ ish hosil bo'ladi. Erta to'xtash tekshiruvi bilan, eng yaxshi holat (array allaqachon saralangan) O(n) ga tushadi: bitta pass hech narsani swap qilish shart emasligini tasdiqlaydi va algoritm darhol to'xtaydi.
Xotira: O(1). Bubble sort elementlarni xuddi shu array ichida, bitta vaqtinchalik swap yordamida qayta joylashtiradi โ u hech qachon ikkinchi array yoki kirish hajmiga qarab o'sadigan boshqa struktura ajratmaydi, shuning uchun xotira sarfi array qanchalik katta bo'lishidan qat'i nazar doimiy qoladi.
n - 1 - i, since the last i elements are already in their final position.arr[j], arr[j+1] = arr[j+1], arr[j], which reads both sides before writing either.range(n - i) instead of range(n - 1 - i), which lets j reach one index past the intended pair and risks an out-of-bounds access. Fix: always compare arr[j] to arr[j+1], so j's maximum must leave room for j+1.n - 1 - i gacha loop qiling, chunki oxirgi i ta element allaqachon o'z joyida.arr[j], arr[j+1] = arr[j+1], arr[j] โ bu yozishdan oldin ikkala tomonni ham o'qiydi.range(n - i) deb yozish, range(n - 1 - i) o'rniga โ bu jning mo'ljallangan juftlikdan bitta index oshib ketishiga va chegaradan chiqib ketish xavfiga olib keladi. Yechim: har doim arr[j] ni arr[j+1] bilan solishtiring, shuning uchun jning maksimal qiymati j+1 uchun joy qoldirishi kerak.sorted() / list.sort() (Timsort) or a proper O(n log n) algorithm like merge sort will always outperform it.sorted() / list.sort() (Timsort) funksiyasi yoki merge sort kabi to'g'ri O(n log n) algoritm doim undan ustun bo'ladi.Restated: given an integer array nums, sort it in ascending order and return it.
sortArray(nums) must return nums sorted ascending โ nothing more exotic than the sorting we've already been doing by hand.sorted() uses a refined relative of it under the hood.def sortArray(nums):
# Bubble sort solves LeetCode 912 correctly, but its O(n^2)
# time causes Time Limit Exceeded on the largest test cases.
# An O(n log n) approach (e.g. merge sort) is required to pass.
n = len(nums)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
if not swapped:
break # a pass with no swaps means nums is sorted
return nums
Qayta bayon: nums butun sonlar array'i berilgan โ uni o'sish tartibida saralab, qaytaring.
sortArray(nums) funksiyasi numsni o'sish tartibida saralab qaytarishi kerak โ biz qo'lda qilib kelgan saralashdan boshqa hech narsa emas.sorted() funksiyasi ham shunga o'xshash, takomillashtirilgan versiyasidan foydalanadi.def sortArray(nums):
# Bubble sort solves LeetCode 912 correctly, but its O(n^2)
# time causes Time Limit Exceeded on the largest test cases.
# An O(n log n) approach (e.g. merge sort) is required to pass.
n = len(nums)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
swapped = True
if not swapped:
break # a pass with no swaps means nums is sorted
return nums