[置顶] 【scala 数据结构和算法】Scala实现:冒泡排序
2017-12-18 16:27
513 查看
主要内容:
1、冒泡排序算法原理
2、scala实现
3、python实现
4、goland实现
冒泡排序算法原理:
1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3、针对所有的元素重复以上的步骤,除了最后一个。
4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较
scala实现:
python实现冒泡排序:
go语言实现冒泡排序:
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
相关文章推荐
- [置顶] 【scala 数据结构和算法】Scala实现:归并排序
- scala数据结构和算法-03-冒泡排序实现
- [置顶] 【scala 数据结构和算法】Scala实现:快速排序
- scala数据结构和算法-04-快速排序实现
- scala数据结构和算法-02-用模式匹配实现合并排序
- 一步步学习数据结构和算法之冒泡排序效率分析及java实现
- [置顶] 【javascript 数据结构与算法】javascript实现冒泡排序
- scala数据结构和算法-05-插入排序实现
- 数据结构与算法——三种基础排序算法C#实现(冒泡排序、选择排序、插入排序)
- 经典算法与数据结构的c++实现——冒泡排序
- scala数据结构和算法-01-用scala实现合并排序
- python数据结构与算法——冒泡排序
- 用Python实现的数据结构与算法:队列
- 【数据结构与算法】【排序】冒泡排序的代码实现
- [置顶] A*寻路算法的lua实现
- 《 常见算法与数据结构》符号表ST(2)——初等实现分析和有序符号表
- 【算法数据结构Java实现】折半查找
- 【数据结构和算法】栈的java实现和栈的应用举例
- Python实现的数据结构与算法之双端队列详解
- 白话经典算法系列之一 冒泡排序的三种实现