Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

how to perform sort array of integer in swift manually without methods available?

input:

let arrayInt = [7,8,3,4,5,9,1,2,6]

output

let newArray = [1,2,3,4,5,6,7,8,9]

how to do that WITHOUT using .sort method that available in Swift? I just failed in programming test, so I want to know the answer :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hey look at this may help you, there are more then 1 possibilities: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html

There is an example: https://gist.github.com/tmdvs/d8edeb9bf26f2f5c3e50

EDIT: Here you have an example:

var unsortedArray = [7,8,3,4,5,9,1,2,6]



for i in stride(from: unsortedArray.count-1, to: 0, by: -1) {
    for j in 1...i {
        if unsortedArray[j-1] > unsortedArray[j] {
            let tmp = unsortedArray[j-1]
            unsortedArray[j-1] = unsortedArray[j]
            unsortedArray[j] = tmp
        }
    }
}

After that the unsortedArray is sorted. Bubble Sort


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...