2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ソートを勉強してみる by Go ②

Posted at

ソートを勉強してみる by Go ① の続き。
クイックソートしてみました。意外とすんなりいきました。

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	length := 20
	list := make([]int, length)
	for i := 0; i < len(list); i++ {
		list[i] = (rand.Int() >> 56)
	}

	sort(list, 0, len(list)-1)

	for i := 0; i < len(list); i++ {
		fmt.Println(list[i])
	}
}

func sort(list []int, start int, end int) {
	if start >= end {
		return
	}
	var stack int

	left := start
	right := end - 1
	marker := end
	for {
		for ; left <= marker; left++ {
			if list[left] > list[marker] {
				break
			}
			if left == marker {
				sort(list, start, end-1)
				return
			}
		}

		for ; right >= left; right-- {
			if right == left {
				stack = list[right]
				list[right] = list[marker]
				list[marker] = stack
				sort(list, start, right-1)
				sort(list, right+1, end)
				return
			}
			if list[right] < list[marker] {
				stack = list[right]
				list[right] = list[left]
				list[left] = stack
				break
			}
		}
	}
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?