常见的排序算法-2.1 选择排序

2020-04-19  本文已影响0人  yulekwok

选择排序(Selection Sort)

  1. 从序列中找出最大的那个元素,然后与最末尾的元素交换位置 执行完一轮后,最末尾的那个元素就是最大的元素

  2. 忽略 1 中曾经找到的最大元素,重复执行步骤 1

    for end := len(this.Array) - 1; end > 0; end-- {
         max := 0
         for begin := 1; begin <= end; begin++ {
             if this.ComWithIndex(begin, begin-1) < 0 {
                 max = begin
             }
         }
         this.Swap(max, end)
     }
    

//选择排序的交换次数要远远少于冒泡排序,平均性能优于冒泡排序
//最好、最坏、平均时间复杂度:O(n2),空间复杂度:O(1),属于不稳定排序

src

package mysort

type SelectionSort struct {
   Sort
}

//1 从序列中找出最大的那个元素,然后与最末尾的元素交换位置 执行完一轮后,最末尾的那个元素就是最大的元素
//2 忽略 1 中曾经找到的最大元素,重复执行步骤 1

//选择排序的交换次数要远远少于冒泡排序,平均性能优于冒泡排序
//最好、最坏、平均时间复杂度:O(n2),空间复杂度:O(1),属于不稳定排序
func (this *SelectionSort) SortFunc() {
   this.Sort.SortFunc()

   for end := len(this.Array) - 1; end > 0; end-- {
      max := 0
      for begin := 1; begin <= end; begin++ {
         if this.ComWithIndex(begin, begin-1) < 0 {
            max = begin
         }
      }
      this.Swap(max, end)
   }

}
package main

import (
    "fmt"
    "iktolin.com/mysort"
    "math/rand"
    "time"
)

func main()  {
    var array []int
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < 40; i++ {
        x := rand.Intn(100)
        array = append(array, x)

    }


    fmt.Println("排序前",array)
    // 时间复杂度 O(n2)
    bubbleSort := mysort.BubbleSort{}
    bubbleSort.SortArray(array)
    bubbleSort.SortFunc()
    bubbleSort.ToString()
    //fmt.Println(array)
    // 使用bool 值判断是否进行过排序,适用于原来就是排好序的
    bubbleSort1 := mysort.BubbleSort{}
    bubbleSort1.SortArray(array)
    bubbleSort1.SortFunc1()
    bubbleSort1.ToString()
    // 使用bool 值判断是否进行过排序,适用于其中有局部排好序的
    bubbleSort2 := mysort.BubbleSort{}
    bubbleSort2.SortArray(array)
    bubbleSort2.SortFunc2()
    bubbleSort2.ToString()


    slect :=mysort.SelectionSort{}
    slect.SortArray(array)
    slect.SortFunc()
    slect.ToString()
    //排序前 [68 23 47 62 33 4 97 49 46 20 25 24 77 88 66 16 6 44 98 11 70 68 30 5 29 46 12 96 31 27 60 24 76 21 19 44 94 46 82 77]
    //排序比较次数 780 排序交换次数 369
    //排序比较次数 725 排序交换次数 369
    //排序比较次数 643 排序交换次数 369
    //排序比较次数 780 排序交换次数 39
}

上一篇 下一篇

猜你喜欢

热点阅读