Go core development study notes (59) - Bubble Sort, sequential search, binary search

Bubble Sort

  1. Focus, numerous interviews were investigated bubble sort
  2. The basic idea of ​​the bubble sort: forward (from the beginning of the next big standard elements) by treating the sort sequence from the sort code once relatively adjacent elements, if found to reverse the exchange, the smaller elements gradually from the sorting code towards the rear.
  3. Because the sorting process, each element constantly close to their location, if no trip down the exchange, a sequence of ordered instructions, to set the sorting process optimization flag is determined whether a flag switching elements, so as to reduce unnecessary comparison.

Bubble Sort detailed breakdown analysis

  1. First there is an array or slice

    • Defined array:

       //方式1
       var array [n]int = [n]int{xx,xx,xx,...}
       //方式2
       var array = [...]int{xx,xx,xx,...}
       //方式3
       var array = make([]int,n)
      
    • Forming an array of incoming external digital

      var n int = 0           //统计元素个数
      fmt.Println("请输入数组的元素个数: ")
      fmt.Scanf("%d", &n)
      var arr []int = make([]int, n)      //定义一个空切片,len为n
      for i := 0; i < n; i++ {
      	var n1 int
      	fmt.Printf("请输入第%d个元素的值:", i+1)
      	fmt.Scanf("%d", &n1)            //每个值都是切片中的一个值
      	arr[i] = n1                     //赋值完毕
      }
      
  2. In order to code reuse, we write a function can be called, named bubbleSort ( ARR * [] int ), to be noted that this function parameter passing must use passing references, modify the main present function () ARR variables, Therefore, the need to pass a pointer type variables .

    func bubbleSort(arr *[]int) {
    	temp := 0                                 //定义一个中间变量当做交换值传递媒介
    	for i := 0; i < len(*arr)-1; i++ {        //外循环为确定最值的循环次数,所以为(数组元素-1)次
    		for j := 0; j < len(*arr)-1-i; j++ {  //内循环次数为元素两两交换次数,由于每外循环一次,最元素就不用再次比较,所以可以减少一次比较,随着外循环次数上升而减少
    			if (*arr)[j] < (*arr)[j+1] {      //元素j < 元素j+1 就交换,最后就是降序排列;
    				temp = (*arr)[j]              //元素j > 元素j+1就交换,那么就是升序排列。
    				(*arr)[j] = (*arr)[j+1]
    				(*arr)[j+1] = temp
    			}
    		}
    	}
    }
    

The final code is as follows:

 package main
 import "fmt"
 
 func bubbleSort(arr *[]int) {
 	temp := 0
 	for i := 0; i < len(*arr)-1; i++ {
 		for j := 0; j < len(*arr)-1-i; j++ {
 			if (*arr)[j] > (*arr)[j+1] {
 				temp = (*arr)[j]
 				(*arr)[j] = (*arr)[j+1]
 				(*arr)[j+1] = temp
 			}
 		}
 	}
 }
 
 func main() {
 	/*
 		构建一个切片
 	*/
 	var n int
 	fmt.Println("请输入切片的元素个数: ")
 	fmt.Scanf("%d", &n)
 	var arr []int = make([]int, n)
 	for i := 0; i < n; i++ {
 		var n1 int
 		fmt.Printf("请输入第%d个元素的值:", i+1)
 		fmt.Scanf("%d", &n1)
 		arr[i] = n1
 	}
 	fmt.Println(arr)
 	/*
 		开始冒泡排序算法,从小到大排列(升序),从大到小排列(降序)
 	*/
 	bubbleSort(&arr)
 	fmt.Println(arr)
 }

Sequential search

Sequential search, for example:

The first way: long-winded

package main
import "fmt"
func main() {
	var arr = [...]string{"主宰","美杜莎","幻影刺客","杨叫兽"}
	var heroName string
	fmt.Println("请输入你要查找的对象: ")
	fmt.Scanf("%v",&heroName)

	for i := 0 ; i < len(arr) ; i++ {
		if heroName == arr[i] {
			fmt.Printf("找到%v,下标为%v",heroName,i)
			break
		} else if i == len(arr) - 1 {
			fmt.Printf("没有找到%v",heroName)
		}
	}
}

The second way: to find proof of that is changing the subscript (recommended)

package main

import "fmt"

func main() {
	var arr = [...]string{"主宰","美杜莎","幻影刺客","杨叫兽"}
	var heroName string
	fmt.Println("请输入你要查找的对象: ")
	fmt.Scanf("%v",&heroName)
	index := -1

	for i := 0 ; i < len(arr) ; i++ {
		if heroName == arr[i] {

			index = i
			break
		}
	}
	if index != -1 {
		fmt.Printf("找到%v,下标为%v",heroName,index)
	} else {
		fmt.Printf("没有找到%v",heroName)
	}
}

Binary search

  • Focus, numerous interviews were investigated binary search

  • The basic idea of ​​binary look for: First array must be ordered, which is a necessary condition for binary search.

  • Find the two principle: the two most find an ordered sequence of values ​​and leftindex & rightindex / 2 to obtain a middle of the index, by comparing the target value and find the middle value, the following extensions to give two results:

    • Ascending order array
      arr [middle]> findVal: Results recursive search range becomes Middle ~ leftindex -. 1
      ARR [Middle] <findVal: Results recursive search range becomes +. 1 ~ rightindex Middle
      ARR [Middle] = findVal: exactly, disposable to find
      leftindex == rightindex: last compare
      leftindex> rightindex: not found

    • Arrays in descending order
      arr [middle]> findVal: Results recursive search range becomes +. 1 ~ rightindex Middle
      ARR [Middle] <findVal: Results recursive search range becomes Middle ~ leftindex -. 1
      ARR [Middle] = findVal: exactly , one-time to find
      leftindex == rightindex: last compare
      leftindex> rightindex: not found

    • Compare these two ways also interpretation of why binary search to find much faster than a sequential, because of the continuing dichotomy half done quickly find.

The final code is as follows:

package main

import "fmt"

func binaryFind(slice *[]int,leftin int,rightin int,findVal int) {
	midin := (leftin + rightin) / 2
	if leftin > rightin {
		fmt.Println("查找的内容不存在")
		return
	}
	if (*slice)[midin] > findVal {
		binaryFind(slice,leftin,midin - 1,findVal)
	}
	if (*slice)[midin] < findVal {
		binaryFind(slice,midin + 1,rightin,findVal)
	}
	if (*slice)[midin] == findVal {
		fmt.Println("找到了,下标为",midin)
	}
}

func main() {
	/*
	 - **重点,众多面试都考察二分查找**
	 - 二分查找的基本思想:首先数组一定要有序,这是进行二分查找的必要条件。
	 - 二分查找的原理:求有序数列 两个最值leftindex&rightindex之和/2 得到一个middle的下标,通过middle下标的值和查找值比较,得到下面两种结果扩展:

	     - **数组从小到大排列**
			arr[middle] > findVal :递归查找结果范围变成 leftindex ~ middle - 1
			arr[middle] < findVal: 递归查找结果范围变成 middle + 1 ~ rightindex
			arr[middle] = findVal: 正好,一次性就找到了
			leftindex == rightindex : 最后一次比较
			leftindex > rightindex :找不到

	     - **数组从大到小排列**
			arr[middle] > findVal :递归查找结果范围变成 middle + 1 ~ rightindex
			arr[middle] < findVal: 递归查找结果范围变成 leftindex ~ middle - 1
			arr[middle] = findVal: 正好,一次性就找到了
			leftindex == rightindex : 最后一次比较
			leftindex > rightindex :找不到
	   - 上述两种比较方式也就诠释了为何二分查找比顺序查找快很多,因为不断二分二分迅速完成查找。
	 */

	var arr = [...]int{2,3,4,6,8}
	slice := arr[:]
	binaryFind(&slice,0,4,2)
}
Published 49 original articles · won praise 18 · views 4010

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/89856943