1. 程式人生 > >排序演算法總結之桶排序 Bucket Sort

排序演算法總結之桶排序 Bucket Sort

private void bucketsort(double[] A)
	{
		int n = A.length;
		ArrayList<Double>[] list = new ArrayList[n];
		
		for(int i=0;i<n;i++)
		{
			int temp = (int)Math.floor(n*A[i]);
			if(list[temp]==null)
				list[temp] = new ArrayList<Double>();
			list[temp].add(A[i]);
		}
		
		for(int i=0;i<n;i++)
			if(list[i]!=null)
				insertionsort(list[i]);
		
		int count = 0;
		for(int i=0;i<n;i++)
		{
			if(list[i]!=null)
			{
				Iterator it = list[i].iterator();
				while(it.hasNext())
				{
					A[count] = (Double)it.next();
					count++;
				}
			}
		}
	}
	
	private void insertionsort(ArrayList<Double> B)
	{
		if(B.size()>1)
		{
			for(int i=1;i<B.size();i++)
			{
				double key = B.get(i);
				int j=i-1;
				while(j>=0 && B.get(j)>key)
				{
					B.set(j+1, B.get(j));
					j--;
				}
				B.set(j+1, key);
			}
		}
	}