insertion sort
This commit is contained in:
		
							parent
							
								
									0e9394e9e1
								
							
						
					
					
						commit
						62b4399322
					
				
					 3 changed files with 39 additions and 1 deletions
				
			
		
							
								
								
									
										16
									
								
								sorting/insertion.go
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								sorting/insertion.go
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,16 @@ | |||
| package sorting | ||||
| 
 | ||||
| type insertion struct{} | ||||
| 
 | ||||
| func (*insertion) Sort(items Sortable) { | ||||
| 	len := items.Len() | ||||
| 	for i := 1; i < len; i++ { | ||||
| 		for j := i; j > 0 && items.Less(j, j-1); j-- { | ||||
| 			items.Swap(j, j-1) | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func NewInsertion() Sorter { | ||||
| 	return &insertion{} | ||||
| } | ||||
|  | @ -7,3 +7,19 @@ import ( | |||
| func TestSelection(t *testing.T) { | ||||
| 	CheckSorter(NewSelection()) | ||||
| } | ||||
| 
 | ||||
| func BenchmarkSelection(b *testing.B) { | ||||
| 	for i := 0; i < b.N; i++ { | ||||
| 		BenchmarkSort(10000, NewSelection()) | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func TestInsertion(t *testing.T) { | ||||
| 	CheckSorter(NewInsertion()) | ||||
| } | ||||
| 
 | ||||
| func BenchmarkInsertion(b *testing.B) { | ||||
| 	for i := 0; i < b.N; i++ { | ||||
| 		BenchmarkSort(10000, NewInsertion()) | ||||
| 	} | ||||
| } | ||||
|  |  | |||
|  | @ -24,7 +24,7 @@ func SameInts(a, b []int) bool { | |||
| func CheckSorter(s Sorter) { | ||||
| 	rand.Seed(time.Now().Unix()) | ||||
| 
 | ||||
| 	actual := rand.Perm(100) | ||||
| 	actual := rand.Perm(1000) | ||||
| 	expected := make([]int, len(actual)) | ||||
| 	copy(expected, actual) | ||||
| 
 | ||||
|  | @ -35,3 +35,9 @@ func CheckSorter(s Sorter) { | |||
| 		log.Fatalf("wrong order:\n actual:\t%v\n expected:\t%v\n", actual, expected) | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func BenchmarkSort(numItems int, s Sorter) { | ||||
| 	rand.Seed(time.Now().Unix()) | ||||
| 	items := rand.Perm(numItems) | ||||
| 	s.Sort(IntSort(items)) | ||||
| } | ||||
|  |  | |||
		Loading…
	
	Add table
		
		Reference in a new issue