4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Goで基本的なアルゴリズム書いてみた

Posted at

概要

基本的なアルゴリズムをGoで書いてみた。

また書いたら追記していく。

線形探索

func LinearSearch(array []int, target int) int {
	for i, v := range array {
		if v == target {
			return i
		}
	}
	return -1
}

バブルソート

// 昇順
func BubbleAscSort(array []int) []int {
	n := len(array)
	for i := 0; i < n-1; i++ {
		for j := 0; j < n-1-i; j++ {
			if array[j] > array[j+1] {
				tmp := array[j]
				array[j] = array[j+1]
				array[j+1] = tmp
			}
		} 
	}
	return array
}

// 降順
func BubbleDescSort(array []int) []int {
	n := len(array)
	for i := 0; i < n-1; i++ {
		for j := 0; j < n-1-i; j++ {
			if array[j] < array[j+1] {
				tmp := array[j]
				array[j] = array[j+1]
				array[j+1] = tmp
			}
		} 
	}
	return array
}

二分探索

func BinarySearch(array []int, target int) int {
	left, right := 0, len(array) - 1

	for left <= right {
		mid := left + (right - left) / 2
		
		if array[mid] == target {
			return mid
		} else if array[mid] < target {
			left = mid + 1
		} else {
			right = mid - 1
		}
	}

	return -1
}

つづく。。かも

4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?