Implement Bubble Sort
Implement Bubble Sort
Implement the bubble sort algorithm from scratch — without using any built-in sort function. Bubble sort repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. The pass is repeated until the array is fully sorted. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer.
Input format — only if your code reads from stdin
Input format (stdin): - First line: integer n (array size) - Second line: n space-separated integers Output: the integers sorted in ascending order, space-separated.
Approach
Run n-1 outer passes. In each pass, compare each adjacent pair (arr[j], arr[j+1]) and swap if arr[j] > arr[j+1]. An early-exit optimization: if no swap occurs in a pass, the array is already sorted.
Input
Output
- •
1 ≤ n ≤ 1000, -10^6 ≤ elements ≤ 10^6 - •
Time complexity: O(n²) — acceptable for this problem size
More Sorting problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards