Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insertion is not faster than Selection ??? #57

Open
mabc666 opened this issue Aug 12, 2018 · 0 comments
Open

Insertion is not faster than Selection ??? #57

mabc666 opened this issue Aug 12, 2018 · 0 comments

Comments

@mabc666
Copy link

mabc666 commented 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();
		
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant