Four sorting algorithms and two points

1. Bubble sorting

func BubbleSort(slice []int) []int {
i, j, okay, count := 0, 0, true, len(slice)
for i = 0; i  slice[j+1] {
slice[j], slice[j+1] = slice[j+1], slice[j]
okay = false
}
}
if okay {//When there is no position exchange in the round comparison, it means that the sorting has been completed, and the loop can be exited in advance
break
}
}
return slice
}

 

2. Insert sort

 func InsertSort(slice []int) []int {
var i, j int
count := len(slice)
for i = 1; i  0; j-- {//Find the insertion position by comparison
if slice[j-1]> slice[j] {
slice[j-1], slice[j] = slice[j], slice[j-1]
} else {//The current element has found the insertion position, exit the loop
break
}
}
}
return slice
}

  

3. Select sorting

 func SelectSort(slice []int) []int {
var i, j, minKey int
count := len(slice)
for i = 0; i  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] = start && slice[j]> val {
j--
}
if i <= j {
slice[i], slice[j] = slice[j], slice[i]
i++
j--
}
}

if start  ​​i {
QuickSort(slice, i, end)
}
}

  

5. Binary search

 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] 

func BubbleSort( slice []int) []int {
i, j, okay, count := 0, 0, true, len(slice)
for i = 0; i  slice[j+1] {
slice[j], slice[j+1] = slice[j+1], slice[j]
okay = false
}
}
if okay {//When there is no position exchange in the round comparison, it means that the sorting has been completed, and the loop can be exited in advance
break
}
}
return slice
}

func InsertSort(slice []int ) []int {
var i, j int
count := len(slice)
for i = 1; i  0; j-- {//Find the insertion position by comparison
if slice[j-1]> slice[j] {
slice[j-1], slice[j] = slice[j], slice[j-1]
} else {//The current element has found the insertion position, exit the loop
break
}
}
}
return slice
}

func SelectSort(slice []int ) []int {
var i, j, minKey int
count := len(slice)
for i = 0; i  slice[j] {
minKey = j
}
}
if minKey != i {
slice[minKey], slice[i] = slice[i], slice[minKey]
}
}
return slice
}

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] = start && slice[j]> val {
j--
}
if i <= j {
slice[i], slice[j] = slice[j], slice[i]
i++
j--
}
}

if start  ​​i {
QuickSort(slice, i, end)
}
}

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] 

Leave a Comment

Your email address will not be published.