Four kinds of sorting algorithms to find and half

1. Bubble Sort

FUNC the BubbleSort (Slice [] int) [] int { 
	I, J, Okay, count: = 0, 0, to true, len (Slice) 
	for I = 0; I <count-. 1; I ++ {// up required count Comparative wheel -1 
		Okay = to true 
		for J = 0; J <-COUNT-I. 1; each of J ++ {// a logical comparison of 
			IF Slice [J]> Slice [J +. 1] { 
				Slice [J], Slice [ . 1 + J] = Slice [J +. 1], Slice [J] 
				Okay to false = 
			} 
		} 
		iF Okay {// when the wheel exchange occurs no positional comparison, description has been sorted complete, exit the loop early 
			BREAK 
		} 
	} 
	return Slice 
}

 

2. Insertion Sort

InsertSort FUNC (Slice [] int) [] {int 
	var I, J int 
	COUNT: = len (Slice) 
	for I =. 1; I <COUNT; I ++ { 
		for J = I; J> 0; // {J, by comparison, to find the insertion position 
			IF Slice [-J. 1]> Slice [J] { 
				Slice [-J. 1], Slice [J] = Slice [J], Slice [-J. 1] 
			} of the current element is the else {// find the insertion position, exit the loop 
				BREAK 
			} 
		} 
	} 
	return Slice 
}

  

3. Select Sort

func SelectSort(slice []int) []int {
	var i, j, minKey int
	count := len(slice)
	for i = 0; i < count-1; i++ {
		minKey = i
		for j = i + 1; j < count; j++ { //找最小数位置
			if slice[minKey] > slice[j] {
				minKey = j
			}
		}
		if minKey != i {
			slice[minKey], slice[i] = slice[i], slice[minKey]
		}
	}
	return slice
}

  

4. Quick Sort

func QuickSort(slice []int, start, end int) {
	if start >= end {
		return
	}
	i, j := start, end
	val := slice[(i+j)/2]
	for i <= j {
		for i <= end && slice[i] < val {
			i++
		}
		for j >= start && slice[j] > val {
			j--
		}
		if i <= j {
			slice[i], slice[j] = slice[j], slice[i]
			i++
			j--
		}
	}

	if start < j {
		QuickSort(slice, start, j)
	}
	if end > i {
		QuickSort(slice, i, end)
	}
}

  

5. 二分查找

func BinarySearch(slice []int, head, tail, value int) int {
	if head > tail {
		return -1
	}
	middle := (head + tail) / 2
	if slice[middle] == value {
		return middle
	} else if slice[middle] < value {
		return BinarySearch(slice, middle+1, tail, value)
	} else {
		return BinarySearch(slice, head, middle-1, value)
	}
}

  

Guess you like

Origin www.cnblogs.com/wujuntian/p/11612892.html