Skip to content

Instantly share code, notes, and snippets.

@kos9kus
Created December 16, 2018 13:53
Show Gist options
  • Save kos9kus/fd471973556d2feb3e99107bef5bfdcf to your computer and use it in GitHub Desktop.
Save kos9kus/fd471973556d2feb3e99107bef5bfdcf to your computer and use it in GitHub Desktop.
//
// 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