Sorting algorithms/Cycle sort

From Rosetta Code
Revision as of 03:05, 12 June 2014 by rosettacode>Mwn3d (Start as a draft, don't add the sorting algorithms box yet)
Sorting algorithms/Cycle sort is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

For more information on cycle sorting, see the Wikipedia entry.

Go

This implementation was translated from the example code on Wikipedia.

<lang go>package main

import ( "fmt" "math/rand" "time" )

func cyclesort(ints []int) int { writes := 0

for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ { item := ints[cyclestart]

pos := cyclestart

for i := cyclestart + 1; i < len(ints); i++ { if ints[i] < item { pos++ } }

if pos == cyclestart { continue }

for item == ints[pos] { pos++ }

ints[pos], item = item, ints[pos]

writes++

for pos != cyclestart { pos = cyclestart for i := cyclestart + 1; i < len(ints); i++ { if ints[i] < item { pos++ } }

for item == ints[pos] { pos++ }

ints[pos], item = item, ints[pos] writes++ } }

return writes }

func main() { rand.Seed(time.Now().Unix())

ints := rand.Perm(10)

fmt.Println(ints) fmt.Printf("writes %d\n", cyclesort(ints)) fmt.Println(ints) }</lang>

Output:
[1 9 3 5 8 4 7 0 6 2]
writes 10
[0 1 2 3 4 5 6 7 8 9]

Note: output may be different due to the random numbers used.