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

Wednesday, September 11, 2013

Radix Sort in python

Here is the radix sort implementation in Python. The efficiency of the Radix Sort algorithm is based on the initial assumptions. According to the assumptions made it could be better or worse than other comparison based sorting algorithms. Mostly when the number of digits are constant it does better.
# usr/bin/env python
import math
aList = [5,67,5,34,64,76,44,56,4,3,7,8,5]
def radixsort( aList ):
RADIX = 10
maxLength = False
tmp , placement = -1, 1
while not maxLength:
maxLength = True
# declare and initialize buckets
buckets = [list() for _ in range( RADIX )]
# split aList between lists
for i in aList:
tmp = i / placement
buckets[int(tmp % RADIX)].append( i )
if maxLength and tmp > 0:
maxLength = False
# empty lists into aList array
a = 0
for b in range( RADIX ):
buck = buckets[b]
for i in buck:
aList[a] = i
a += 1
# move to next digit
placement *= RADIX
print(aList)
radixsort(aList)
print(aList)
view raw RadixSort.py hosted with ❤ by GitHub