Sunday, August 1, 2021

Java Bubble sort

In bubble sort we pick first element and compare with each elements. If right element is bigger with first element, we will swap the elements. Similarly we will pick next element and compare with each elements and swap if found and bigger value or right hand side.

So in the first iteration first element will be in sorted order. As you can see in below example.

unsorted array : {23, 3, 4, 1, 6, 34}

1- iteration  {1, 23, 4, 3, 6, 34}

2- iteration  {1, 3, 23, 4, 6, 34}

3 -iteration  {1, 3, 4, 23, 6, 34}

4- iteration  {1, 3, 4, 6, 23, 34}

5- iteration  {1, 3, 4, 6, 23, 34}

Worst case time complexity is O(n^2), it is simple but inefficient way of sorting.


public class BubbleSort {

public static void main(String[] args) {

int[] data = {23,3,4,1,6,34};

int length  = data.length;

int temp = 0;

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

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

if(data[i]>data[j]) {

temp = data[j];

data[j]=data[i];

data[i]=temp;

}

}

}

for (int k : data) {

System.out.println(k);

}

}

}

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home