一、swift实例
1、冒泡法
(1).只能按一种方式排序
//冒泡
var a = [2,8,4,10,31,12]
for i in 0..<a.count - 1 {//循环多少次
for j in 0..<(a.count - i - 1) {//比较多少次
//比较转换位置
if (a[j] > a[j+1]) {
let temp = a[j]
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
print(a)
(2).使用闭包
//函数
func upsort(num:Int,num1:Int)->Bool{
return num > num1 ? true : false
}
//闭包
let downsort:(Int,Int)->Bool = {
return $0 < $1
}
var arr2 = [2,5,1,4,7,6,0,18];
func sortArray(sortFun:(Int,Int)->Bool) {
for i in 0..<arr2.count - 1 {
for j in 0..<arr2.count - 1 - i {
if (sortFun(arr2[j],arr2[j+1])){
let temp=arr2[j]
arr2[j]=arr2[j+1]
arr2[j+1] = temp
}
}
}
print(arr2)
}
//调用函数升序排列
sortArray(sortFun:upsort)
//使用闭包降序
sortArray(sortFun:downsort)
2、层级遍历
import Foundation
class Node: NSObject {
//!强制拆包(解析)
var date: Int!
var leftChild: Node? //?可选类型
var rightChild: Node?
}
//创建类对象
var node1 : Node = Node()
node1.date = 4
var node2 : Node = Node()
node2.date = 5
var node3 : Node = Node()
node3.date = 6
var node4 : Node = Node()
node4.date = 7
var node5 : Node = Node()
node5.date = 2
node5.leftChild = node1
node5.rightChild = node2
var node6 : Node = Node()
node6.date = 3
node6.leftChild = node3
node6.rightChild = node4
var node7 : Node = Node() //根节点
node7.date = 1
node7.leftChild = node5
node7.rightChild = node6
//定义空数组,将节点和根节点放进数组然后输出数组
func readDate(node : Node){
var arr = [Node]()
arr.append(node) //插入节点
while arr.count > 0 {
let t = arr[0]
if let _ = t.leftChild {//可选绑定,判断是否有左右子叶,如果有添加到数组中
arr.append(t.leftChild!)
}
if let _ = t.rightChild{
arr.append(t.rightChild!)
}
print(t.date)
arr.remove(at: 0)
}
}
readDate(node:node7)