- the keys of the items that we wish to sort lie in a small fixed range and
- that there is only one item with each value of the key.
- Set up an array of "bins" - one for each value of the key - in order,
- Examine each item and use the value of the key to place it in the appropriate bin.
Constraints on bin sort
To understand these restrictions, let's be a little more precise about the specification of the problem and assume that there are m values of the key. To recover our sorted collection, we need to examine each bin. This adds a third step to the algorithm above,- Examine each bin to see whether there's an item in it.
Procedure Bin_Sort(int a[], int bin[], int n)
1. for i=0 to M do where M is 0<= a[i] < M
2. bin[i] = -1;
3.end for
4.for i=0 to n do
5.bin[a[i]]=a[i];
6.end for
If there are duplicates, then each bin can be replaced by a linked list. The third step then becomes:
- Link all the lists into one list.
Having highlighted this constraint, there is a version of bin sort which can sort in place:
Procedure Bin_Sort(int a[], int n)
1.for i=0 to n do
2. if ( a[i] != i )
3. SWAP( a[i], a[a[i]] );
4. end if
5. end for
However, this assumes that there are n distinct keys in the range 0 .. n-1. In addition to this restriction, the SWAP operation is relatively expensive, so that this version trades space for time.
Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package algorithm; | |
/** | |
* | |
* @author sutha | |
*/ | |
public class binsort | |
{ | |
public int find_max(int a[]) | |
{ | |
int max=0; | |
for(int i=0;i<a.length;i++) | |
{ | |
if(a[i]>max) | |
{ | |
max=a[i]; | |
} | |
} | |
return max; | |
} | |
public void bin_sort(int a[],int bin[], int n) | |
{ | |
int m=find_max(a); | |
for(int i=0;i<m+1;i++) | |
{ | |
bin[i]=-1; | |
} | |
for(int i=0;i<n;i++) | |
{ | |
bin[a[i]]=a[i]; | |
} | |
} | |
public void print(int[] a) | |
{ | |
for(int i=0;i<a.length;i++) | |
{ | |
if(a[i]>0) | |
{ | |
System.out.print(a[i] + " "); | |
} | |
} | |
} | |
public static void main(String [] args) | |
{ | |
binsort bs=new binsort(); | |
int a[]={45,58,79,75,94,22,13,41,53}; | |
int bin_size=bs.find_max(a); | |
int [] b=new int[bin_size+1]; | |
bs.bin_sort(a,b,a.length); | |
bs.print(b); | |
} | |
} |
0 comments:
Post a Comment