#57·algs4

Insertion is not faster than Selection ???

Author: mabc666Created Aug 12, 2018Updated Aug 12, 2018

According to the book ,i write the sorting code of Insertion and Selection by myself.According to my test ,i find that the Insertion is not faster 1.7 times than Selection. I checkout my code but it is not error.I am very curious.Why is my data so different from the book.My test data is about 0.8 times. Selection sort faster than Insertion sort ?The following is my resource code and test code: Insertion sort code

public static void sort(Comparable[] a)
	{	
		int N = a.length;
		for(int i = 1; i < N; i++)
		{
			for(int j = i; j > 0 && less(a[j], a[j-1]) ; j--)
			{		
				exch(a, j, j-1);
				
			}
		
		}
		assert isSorted(a);
		
	}

Selection sort code   
public static void sort(Comparable[] a)
	{	
		int N = a.length;
		for(int i = 0; i < N; i++)
		{	
			int min = i;
			for(int j = i + 1; j < N; j++)
			{
				if(less(a[j], a[min]))
				{
					min = j;
				}		
			}
			exch(a, i, min);
			
		}
		assert isSorted(a);

	}

test code     

public static void main(String[] args) 
{	int N = 1000;
		int T = 100;
		double t1 = timeRandomInput("Insertion", N, T);
		double t2 = timeRandomInput("Selection", N, T);
		System.out.println(t2/t1);

}
public static double timeRandomInput(String alg, int N, int T) 
	{
		double total = 0.0;
		Double[] a = new Double[N];
		for(int t = 0; t < T; t++)
		{
			for(int i = 0; i < N; i++)
				a[i] = StdRandom.uniform();
			total += time(alg, a);
			
		}
		return total;

	}
public static double time(String alg, Comparable[] a)
	{
		Stopwatch timer = new Stopwatch();
		if(alg.equals("Insertion")) Insertion.sort(a);
		if(alg.equals("Selection")) Selection.sort(a);
		return timer.elapsedTime();
		
	}