Thursday, June 11, 2015

List heap sort implementation in java

Code:


import java.util.Comparator;
import java.util.List;


public class Sort {

	
	private Sort(){throw new AssertionError();}
	
	
	private static <T extends Comparable<? super T>> 
	void heapify(Comparator<? super T> c, int index, List<T> arreglo, int size)
	{
		
		while(2*index+1<size)
		{
			int left= 2*index+1;
			
			if(left<(arreglo.size()-1) && compare(left,left+1,arreglo,c)<0)
				++left;
			
			if(compare(index,left,arreglo,c)>=0)
				break;
				
			exchange(arreglo, index, index=left);
		}
		
	}
	
	public static <T extends Comparable<? super T>> 
	void heapSort( List<T> arreglo, Comparator<? super T> c)
	{
		int last= arreglo.size()-1;
		
		for(int i= (arreglo.size()/2)-1; i>-1;--i)
			heapify(c, i, arreglo, last+1);
			
		while(last>0)
		{
			exchange(arreglo, last--, 0);
			heapify(c, 0, arreglo, last);
		}			
		
	}
	
	public static <T extends Comparable<? super T>> 
	void heapSort( List<T> arreglo)
	{
		heapSort( arreglo, (x,y)->x.compareTo(y));
	}
	
	private static <T extends Comparable<? super T>> 
	void exchange(List<T> arreglo, int index1, int index2)
	{
		arreglo.set(index2,arreglo.set(index1, arreglo.get(index2)));	
	}
	
	private static<T extends Comparable<? super T>> 
	int compare(int index, int index2, List<T> lista, Comparator<? super T> compare)
	{
		
		return compare.compare(lista.get(index),(lista.get(index2)));
		
	}
}

No comments:

Post a Comment