Skip to content

Instantly share code, notes, and snippets.

@williamhqs
Created December 2, 2015 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williamhqs/2a91555b0df2e8f20c40 to your computer and use it in GitHub Desktop.
Save williamhqs/2a91555b0df2e8f20c40 to your computer and use it in GitHub Desktop.
Normal sort algorithm in Swift
//: Playground - noun: a place where people can play
import UIKit
func swap<T>(inout value1: T, inout value2: T) {
let temporary = value1
value1 = value2
value2 = temporary
}
func maxNumer<T: Comparable>(array:[T]) -> (T,Int){
var maxNumer = array[0]
var maxIndex = 0
for var i = 0; i < array.count-1; i++ {
if maxNumer < array[i+1] {
maxNumer = array[i+1]
maxIndex = i+1
}
}
return (maxNumer, maxIndex)
}
/**
Bubble Sort: 冒泡排序
**/
var numbers = [1,3,3,23,67,34,2,7,0,9]
for var times = 0; times < numbers.count; times++ {
for var index = 0; index < numbers.count-1-times; index++ {
if numbers[index] > numbers[index+1] {
swap(&numbers[index], &numbers[index+1])
}
}
}
print(numbers)
/**
Quick Sort: 快速排序
**/
var numbers1 = [3,9,23,67,34,2,7,0,1]
func quickSort(left:Int, _ right: Int) {
if left > right {
return
}
var i=left,j=right
let base = numbers1[left]
while i < j {
while numbers1[j] >= base && i<j {
j--
}
if (i < j){
numbers1[i] = numbers1[j]
}
while numbers1[i] < base && i<j {
i++
}
if (i < j) {
numbers1[j] = numbers1[i]
}
}
if (i==j) {
numbers1[i] = base
}
quickSort(left,i-1)
quickSort(i+1,right)
}
quickSort(0, numbers1.count-1)
print(numbers1)
/**
Selection Sort: 选择排序
**/
var numbers3 = [3,9,23,67,34,2,7,0,1]
for var i = 0; i < numbers3.count; i++ {
var maxIndex = i
for var j = i+1; j < numbers3.count; j++ {
if numbers3[maxIndex] < numbers3[j] {
maxIndex = j
}
}
if i != maxIndex {
swap(&numbers3[i], &numbers3[maxIndex])
}
}
print(numbers3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment