您的位置:首页 > 理论基础 > 数据结构算法

[置顶] 【scala 数据结构和算法】Scala实现:冒泡排序

2017-12-18 16:27 513 查看
主要内容:

1、冒泡排序算法原理

2、scala实现

3、python实现

4、goland实现

冒泡排序算法原理:

1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。

2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。

3、针对所有的元素重复以上的步骤,除了最后一个。

4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较

scala实现:

/**
* Created by Administrator on 2017/12/18.
*/
object BubbleSort {
//  冒泡排序

// 外层循环做拆分
def bubbleSort(l: List[Int]): List[Int]  = l match {
case List() => List()
case head :: tail => bSort(head, bubbleSort(tail))
}

// 内层循环做排序

def bSort(data: Int, dataSet: List[Int]): List[Int] = dataSet match {
case List() => List(data)
case head :: tail => if (data <= head) data :: dataSet else head :: bSort(data, tail)
}

def main(args: Array[String]) {
val list = List(3, 12, 43, 23, 7, 1, 2, 20)
println(bubbleSort(list))
}

}


List(1, 2, 3, 7, 12, 20, 23, 43)

Process finished with exit code 0


python实现冒泡排序:

# encoding: utf-8
from __future__ import division
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def bubble(bubbleList):
listLength = len(bubbleList)
while listLength > 0:
for i in range(listLength - 1):
if bubbleList[i] > bubbleList[i+1]:
bubbleList[i] = bubbleList[i] + bubbleList[i+1]
bubbleList[i+1] = bubbleList[i] - bubbleList[i+1]
bubbleList[i] = bubbleList[i] - bubbleList[i+1]
listLength -= 1
print bubbleList

if __name__ == '__main__':
bubbleList = [3, 12, 43, 23, 7, 1, 2, 20]
bubble(bubbleList)


"D:\Program Files\Python27\python.exe" D:/PycharmProjects/learn2017/冒泡排序.py
[1, 2, 3, 7, 12, 20, 23, 43]

Process finished with exit code 0


go语言实现冒泡排序:

package main

import(
"fmt"
)

func bubbleSort2(nums []int) {
for i := 0; i < len(nums); i++ {
for j := 1; j < len(nums)-i; j++ {
if nums[j] < nums[j-1] {
//交换
nums[j],nums[j-1] = nums[j-1],nums[j]
}
}
}
printArray(nums)
}

func printArray(a []int) {
for i := 0; i < len(a) - 1; i++ {
fmt.Printf("%d, ", a[i])
}
fmt.Print(a[len(a)-1])
}

func main() {
a := []int{3, 12, 43, 23, 7, 1, 2, 20}
printArray(a)
fmt.Printf("\n")
bubbleSort2(a)
fmt.Printf("\n")
}


3, 12, 43, 23, 7, 1, 2, 20
1, 2, 3, 7, 12, 20, 23, 43

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: