Created
December 16, 2018 13:53
-
-
Save kos9kus/fd471973556d2feb3e99107bef5bfdcf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// PutZerosToTheEnd.swift | |
// Test | |
// | |
// Created by KONSTANTIN KUSAINOV on 16/12/2018. | |
// Copyright © 2018 KONSTANTIN KUSAINOV. All rights reserved. | |
// | |
import Foundation | |
struct PutZerosToTheEnd { | |
static func test() { | |
var arr = [1, 9, 0, 0, 0, 14] | |
print("PutZerosToTheEnd = \(arr)") | |
transform(arr: &arr) | |
print("PutZerosToTheEnd: \(arr)") | |
arr = [0, 10, 9, 0, 0, 0, 14, 5] | |
print("=== PutZerosToTheEnd ===") | |
print("PutZerosToTheEnd = \(arr)") | |
transform(arr: &arr) | |
print("PutZerosToTheEnd: \(arr)") | |
} | |
static private func transform(arr: inout [Int]) { | |
let n = arr.count | |
var j = (n - 1) | |
for i in (0...j).reversed() { | |
let val_i = arr[i] | |
if val_i == 0 { | |
self.swapKK(arr: &arr, lhsIndex: i, rhsIndex: j) | |
j -= 1 | |
} | |
} | |
} | |
static func swapKK(arr: inout Array<Int>, lhsIndex: Int, rhsIndex: Int ) { | |
let lhs = arr[lhsIndex] | |
arr[lhsIndex] = arr[rhsIndex] | |
arr[rhsIndex] = lhs | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment