Bubble Sort
Bubble Sort
Topperworld.in
Bubble Sort
Bubble Sort is another simple sorting algorithm that works by repeatedly
stepping through the list to be sorted, comparing each pair of adjacent
items, and swapping them if they are in the wrong order. This process is
repeated for the entire list until no more swaps are needed, indicating that
the list is sorted.
Algorithm:
Bubble_Sort(int a[], n)
{
int swapped, i, j;
for (i=0; i<n; i++)
{
swapped = 0;
for (j=0; j<n-i-1; j++)
{
if (a[j] > a[j+1])
{
swap (a[j], a[j+1]);
swapped = 1;
}
}
if (swapped == 0)
break;
}
}
2. If the first element is greater than the second element, swap them.
©TopperWorld
Data Structure and Algorithm
4. Continue this process until you reach the end of the array. By this
point, the largest element will have "bubbled up" to the end of the
array.
5. Repeat steps 1-4 for the remaining unsorted portion of the array.
2. If the first element is greater than the second element, they are
swapped.
3. Now, compare the second and the third elements. Swap them if they
are not in order.
©TopperWorld
Data Structure and Algorithm
2. Remaining Iteration
The same process goes on for the remaining iterations.
After each iteration, the largest element among the unsorted elements is
placed at the end.
©TopperWorld
Data Structure and Algorithm
©TopperWorld
Data Structure and Algorithm
The array is sorted when all the unsorted elements are placed at their
correct positions.
The array is sorted if all elements are kept in the right order
➔Java Implementation:
©TopperWorld
Data Structure and Algorithm
swapped = true;
}
}
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
OUTPUT
Sorted array:
11 12 22 25 34 64 90
©TopperWorld
Data Structure and Algorithm
➔Complexity Analysis:
©TopperWorld