Bubble Sort
Complexity
The bubble sort makes multiple passes through a list and sometimes
referred to as sinking sort. It is a simple sorting algorithm that compare the adjacent
elements and swap their position if they are nor in intended order. Each pass
through the list places the next largest value in its proper place. In essence,
each item “bubbles” up to the location where it belongs.
So now lets talk about How Bubble sort works?
Lets take an list as shown below
As Shown above, Starting from the first element, two adjacent
elements are compared. If the former element is greater than the latter one,
they are swapped. This process goes on for all consecutive-element pairs until
the last unsorted element.
And again it will follow the same recursive method till the complete
list is sorted.
class BubbleSort{ public void bubbleSort(int array[]){ int size = array.length; for (int i = 0; i < size-1; i++){ for (int j = 0; j < size-i-1; j++){ if (array[j] > array[j+1]){ int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } } Public void printArray(int array[]){ int size = array.length; for(int i=0; i < size; ++i) System.out.print(array[i]+" "); System.out.println(); } public static void main(String args[]){ int[] data = {-2, 45, 0, 11, -9}; BubbleSort bs = new BubbleSort(); bs.bubbleSort(data); System.out.println("Sorted Array in Ascending Order:"); bs.printArray(data); } }
Now lets talk about the complexity of bubble sort.
As Bubble sort is the simplest sorting algorithm and in above java
code we have implemented two foor loops, So the complexity of of this algorithm
is O(n*n) = O(n2 ). This
is the worst case complexity.
Where we can use bubble sort?
1.
Where the complexity of
code does not matters
Where a sort code is refer.
No comments:
Post a Comment