Sitemap
Harshavardhana P

Harshavardhana P

Learn, Grow, Share, Guide and Help Development | Technology | Self Improvement | Fitness | Mindset

Bubble Sort

1 min readJun 6, 2025

This algorithm focuses on moving the highest element to the end by swapping a larger neighboring element to the right.

    Get Harshavardhana P’s stories in your inbox

    Join Medium for free to get updates from this writer.

  1. We perform the operation only n - 1 times (outer loop) because the last element will automatically be in the correct position once the others are sorted.
  2. We maintain a boolean flag to check if any swap occurred during a particular cycle. If no swaps happen, it means the array is already sorted.
  3. Since one element reaches its correct position at the end in each cycle, we reduce the number of inner loop iterations by the current outer loop count, i.e., n - 1 - i. Also, we compare the jth element with the (j + 1)th element.
  4. If the neighboring element is greater, it will be swapped.
public void bubbleSort(int[] arr){

int n=arr.length;

for (int i = 0; i < n-1; i++) {

boolean swapped=false;

for (int j = 0; j < n-i-1; j++) {

if (arr[j]>arr[j+1]) {

swapped=true;

int temp=arr[j+1];

arr[j+1]=arr[j];

arr[j]=temp;

}

}

if(!swapped){

break;

}

}

}

--

--

Harshavardhana P
Harshavardhana P

Written by Harshavardhana P

0 followers

Learn, Grow, Share, Guide and Help Development | Technology | Self Improvement | Fitness | Mindset