SHARE
TWEET

Untitled

a guest Dec 16th, 2018 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  PutZerosToTheEnd.swift
  3. //  Test
  4. //
  5. //  Created by KONSTANTIN KUSAINOV on 16/12/2018.
  6. //  Copyright © 2018 KONSTANTIN KUSAINOV. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. struct PutZerosToTheEnd {
  12.     static func test() {
  13.         var arr = [1, 9, 0, 0, 0, 14]
  14.         print("PutZerosToTheEnd = \(arr)")
  15.         transform(arr: &arr)
  16.         print("PutZerosToTheEnd: \(arr)")
  17.        
  18.         arr = [0, 10, 9, 0, 0, 0, 14, 5]
  19.         print("=== PutZerosToTheEnd ===")
  20.         print("PutZerosToTheEnd = \(arr)")
  21.         transform(arr: &arr)
  22.         print("PutZerosToTheEnd: \(arr)")
  23.     }
  24.    
  25.     static private func transform(arr: inout [Int]) {
  26.         let n = arr.count
  27.        
  28.         var j = (n - 1)
  29.         for i in (0...j).reversed() {
  30.             let val_i = arr[i]
  31.            
  32.             if val_i == 0 {
  33.                 self.swapKK(arr: &arr, lhsIndex: i, rhsIndex: j)
  34.                 j -= 1
  35.             }
  36.            
  37.         }
  38.     }
  39.    
  40.     static func swapKK(arr: inout Array<Int>, lhsIndex: Int, rhsIndex: Int ) {
  41.         let lhs = arr[lhsIndex]
  42.         arr[lhsIndex] = arr[rhsIndex]
  43.         arr[rhsIndex] = lhs
  44.     }
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top