Created
November 22, 2014 19:54
-
-
Save nickcarenza/53ad9211c13d2a2e1d1e to your computer and use it in GitHub Desktop.
Golang FocusedSort with known, unsorted index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package _ | |
import ( | |
"fmt" | |
"log" | |
"math/rand" | |
"sort" | |
"time" | |
) | |
var size = 10000 | |
func main() { | |
floats := make([]float64, size) | |
for i := 0; i < size; i++ { | |
floats[i] = rand.Float64() | |
} | |
slice := sort.Float64Slice(floats) | |
fmt.Printf("Sorted %t \n", sort.IsSorted(slice)) | |
fullSort(slice) | |
fmt.Println("Meddling") | |
slice[500] = rand.Float64() | |
fmt.Printf("Sorted %t \n", sort.IsSorted(slice)) | |
adjustSort(slice) | |
fmt.Println("Meddling") | |
slice[500] = rand.Float64() | |
fmt.Printf("Sorted %t \n", sort.IsSorted(slice)) | |
betterAdjustSort(slice, 500) | |
} | |
func fullSort(slice sort.Interface) { | |
defer un(trace("Full Sort")) | |
sort.Sort(slice) | |
fmt.Printf("Sorted %t \n", sort.IsSorted(slice)) | |
} | |
func adjustSort(slice sort.Interface) { | |
defer un(trace("Adjust Sort")) | |
sort.Sort(slice) | |
fmt.Printf("Sorted %t \n", sort.IsSorted(slice)) | |
} | |
// FocusedSort takes index argument and just sorts that index in the slice. | |
// Sorts ascending by default | |
func betterAdjustSort(slice sort.Interface, i int) { | |
defer un(trace("Better Adjust Sort")) | |
// Sort ascending | |
for slice.Less(i, i-1) { | |
slice.Swap(i, i-1) | |
i-- | |
} | |
for slice.Less(i+1, i) { | |
slice.Swap(i+1, i) | |
i++ | |
} | |
// Sort descending | |
// for slice.Less(i, i+1) { | |
// slice.Swap(i, i+1) | |
// i++ | |
//} | |
//for slice.Less(i-1, i) { | |
// slice.Swap(i-1, i) | |
// i-- | |
//} | |
fmt.Printf("Sorted %t \n", sort.IsSorted(slice)) | |
} | |
// Timing functions | |
func trace(s string) (string, time.Time) { | |
startTime := time.Now() | |
log.Printf("START: %s\n", s) | |
return s, startTime | |
} | |
func un(s string, startTime time.Time) { | |
log.Printf(" END: %s Elapsed Time: %s\n", s, time.Since(startTime)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment