Bubble sorting an array in Swift, compiler error on swap

前端 未结 6 1234
闹比i
闹比i 2021-01-20 05:22

I wrote a really simple bubble sort for a card game. It takes an array of \"Card\" objects, each of which has a an \"order\" attribute which indicates the value to be sorted

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 05:26

    Here is bubble sort implemented in swift 4.0.2

    var array = [15,11,20,14,12,13,17,16,18,19]
    var sortedArray = Array(array)
    var sortedAboveIndex = array.count 
    
    for i in 0 ..< sortedAboveIndex-1 {
    
      for j in 0 ..< sortedAboveIndex-i-1 {
    
          if (sortedArray[j] > sortedArray[j+1]) {
    
              sortedArray.swapAt(j, j+1)        
          }
      }
    
    }
    
    print(sortedArray)
    

    if any queries on above code please comment below

提交回复
热议问题