Sorting ALGO
Sorting ALGO
Tutorials
Bubble Sort is the simplest sorting algorithm that repeatedly swaps the
adjacent elements if they are in the wrong order. This algorithm is unsuitable
for large data sets as its average and worst-case time complexity is quite
high.
Bubble Sort Algorithm
In the Bubble Sort algorithm,
Traverse from the left and compare adjacent elements and the higher one
is placed at the right side.
In this way, the largest element is moved to the rightmost end at first.
This process is then continued to find the second largest and place it and
so on until the data is sorted.
import java.util.Arrays;
int count = 0;
// One pass of bubble sort. After
// this pass, the largest element
// is moved (or bubbled) to end.
for (int i=0; i<n-1; i++)
if (arr[i] > arr[i+1])
{
// swap arr[i], arr[i+1]
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
count = count+1;
}
// Driver Method
public static void main(String[] args)
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr, arr.length);
Worst Case: The worst-case condition for bubble sort occurs when
elements of the array are arranged in decreasing order.
In the worst case, the total number of iterations or passes required to sort
a given array is (N-1). where ‘N’ is the number of elements present in the
array.
At pass 1:
At pass 2:
At pass 3:
At pass N-1:
Number of comparisons = 1
Number of swaps = 1
= (N * (N-1)) / 2