Tuesday, September 17, 2013

Bubblesort algorithm in Java

Given below is the Bubblesort algorithm in Java. Although bubblesort is not a efficient algorithm, its a simple algorithm to demonstrate what is a sorting algorithm


Asymptotic Complexity
Time ComplexitySpace Complexity
n^21


If you want to see the same implementation in python please click the following link: Bubblesort implementation in python

If you would like to see how this implentation would look like in C click the following link: Bubblesort implementation in C
public class BBSort
{
private void bubblesort(int [] arr)
{
int i = 1, temp;
boolean swapped = true;
while(swapped)
{
swapped = false;
for(int j=0; j < arr.length - i ; j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}
}
i++;
}
}
public static void main(String []args)
{
int [] arr = { 12,34,32,5,6,2,3,4,23,34,233,64,64,3,634,43,322,3232,3};
for (int i=0; i < arr.length; i++)
System.out.print(" " +arr[i]);
BBSort b = new BBSort();
b.bubblesort(arr);
System.out.println();
for (int i=0; i < arr.length; i++)
System.out.print(" " +arr[i]);
}
}
view raw BBSort.java hosted with ❤ by GitHub

No comments:

Post a Comment