【scala 資料結構和演算法】Scala實現:氣泡排序
阿新 • • 發佈:2019-02-20
主要內容:
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