A single-loop version of bubble sort
A teaching example of bubble sort written with one loop, including why it is not actually faster than standard sorting functions.
Bubble sort orders an array by comparing neighbouring elements and swapping them. The classic version uses two nested loops. The example below does the same work with a single loop: whenever a swap happens the counter steps back, so the array is revisited as many times as needed.
It looks shorter but it is not faster: the number of comparisons is unchanged and stays proportional to the square of the element count in the worst case. The gain is in readability and code size.
Bubble sort is not the right choice in production; the sort function in your language's standard library is both faster and battle-tested. The value here is educational — it shows how manipulating a loop counter can steer the flow of an algorithm.
int[] arr = { 16, 12, 24, 21, 13, 9, 17, 8, 2, 14, 30, 26, 4, 19, 10, 15, 3, 27, 1, 22, 11, 6, 5, 18, 28, 7, 29, 20, 25, 23 };
int n = arr.Length;
int temp = 0;
for (int i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
{
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
i-=2;
i = ((i < -1) ? -1 : i);
}
}
var arr = [16, 12, 24, 21, 13, 9, 17, 8, 2, 14, 30, 26, 4, 19, 10, 15, 3, 27, 1, 22, 11, 6, 5, 18, 28, 7, 29, 20, 25, 23];
var n = arr.length;
var temp = 0;
for (var i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
{
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
i-=2;
}
}
arr = [16, 12, 24, 21, 13, 9, 17, 8, 2, 14, 30, 26, 4, 19, 10, 15, 3, 27, 1, 22, 11, 6, 5, 18, 28, 7, 29, 20, 25, 23]
n = len(arr)
i = 0
while i < n - 1:
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i+1], arr[i]
i -= 2
i = -1 if i < -1 else i
i += 1
Short guide
When to use it
Bubble sort is rarely the right choice for production code, but it is a good teaching example for loops, comparisons and swapping values. Use it to understand the idea, not to sort large datasets.
What to watch
- Do not use this algorithm for large lists; performance drops quickly.
- Write the comparison direction clearly.
- In real applications, built-in sorting functions are usually faster and safer.
Common mistake
A teaching algorithm should not be moved into production just because it works in a small example. Larger data needs a different approach.
Where this example helps
Small helper snippets like this save time in web applications, mobile app backends, admin panels and API projects. The important part is not copying the example blindly, but adapting it to your data format, security needs and performance expectations.