Search Your Question

Write a program for sorting array. Quick sort, merge sort, Heap Sort

Ans : 

Quick Sorting Integer Array - Explanation


func swap<T: Comparable>(leftValue: inout T, rightValue: inout T) {
    (leftValue, rightValue) = (rightValue, leftValue)
}

func partition<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) -> Int {
    var q = startIndex
    for index in startIndex..<endIndex {
        if array[index] < array[endIndex] {
            swap(leftValue: &array[q], rightValue: &array[index])
            q += 1
        }
    }
    swap(leftValue: &array[q], rightValue: &array[endIndex])
    return q
}
func quickSort<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) {
    // Base case
    if startIndex >= endIndex {
        return
    }
    let placedItemIndex = partition(array: &array, startIndex: startIndex, endIndex: endIndex)
    quickSort(array: &array, startIndex: startIndex, endIndex: placedItemIndex-1)
    quickSort(array: &array, startIndex: placedItemIndex+1, endIndex: endIndex)
}
func quickSort<T: Comparable>(array: inout [T]) {
    quickSort(array: &array, startIndex: 0, endIndex: array.count-1)
}
var numbers = [13, 77, 20, 45, 2, 15, 0, 59, 5, 68, 51, 1, -1, 77]

quickSort(array: &numbers)


Merge Sorting Integer Array - Explanation


func merge<T: Comparable> (array: inout [T], startIndex: Int, middleIndex: Int, endIndex: Int) {
    let leftSubarray = Array(array[startIndex...middleIndex])
    let rightSubarray = Array(array[middleIndex+1...endIndex])
    var index = startIndex
    var leftIndex = 0
    var rightIndex = 0
    while leftIndex < leftSubarray.count && rightIndex < rightSubarray.count {
        if leftSubarray[leftIndex] < rightSubarray[rightIndex] {
            array[index] = leftSubarray[leftIndex]
            leftIndex += 1
        }
        else {
            array[index] = rightSubarray[rightIndex]
            rightIndex += 1
        }
        index += 1
    }
    while leftIndex < leftSubarray.count {
        array[index] = leftSubarray[leftIndex]
        index += 1
        leftIndex += 1
    }
    while rightIndex < rightSubarray.count {
        array[index] = rightSubarray[rightIndex]
        index += 1
        rightIndex += 1
    }
}

func mergeSort<T: Comparable>(array: inout [T], startIndex: Int, endIndex: Int) {
    // Base case
    if startIndex >= endIndex {
        return
    }
    let middleIndex = (startIndex + endIndex) / 2
    mergeSort(array: &array, startIndex: startIndex, endIndex: middleIndex)
    mergeSort(array: &array, startIndex: middleIndex+1, endIndex: endIndex)
    merge(array: &array, startIndex: startIndex, middleIndex: middleIndex, endIndex: endIndex)
}
func mergeSort<T: Comparable>(array: inout [T]) {
    mergeSort(array: &array, startIndex: 0, endIndex: array.count-1)
}

var numbers = [13, 77, 20, 45, 2, 15, 0, 59, 5, 68, 51, 1, -1, 77]
mergeSort(array: &numbers)





Heap Sorting Integer Array - Explanation

extension Heap {
    public mutating func sort() -> [T] {
        for i in stride(from: (nodes.count - 1), through: 1, by: -1) {
            nodes.swapAt(0, i)
            shiftDown(from: 0, until: i)
        }
        return nodes
    }
}
/*
 Sorts an array using a heap.
 Heapsort can be performed in-place, but it is not a stable sort.
 */
public func heapsort<T>(_ a: [T], _ sort: @escaping (T, T) -> Bool) -> [T] {
    let reverseOrder = { i1, i2 in sort(i2, i1) }
    var h = Heap(array: a, sort: reverseOrder)
    return h.sort()
}

//Testing
func testSort() {
    var h1 = Heap(array: [5, 13, 2, 25, 7, 17, 20, 8, 4], sort: >)
    let a1 = h1.sort()
}

// output : [2, 4, 5, 7, 8, 13, 17, 20, 25]


Difference between category in Objective C and extension Swift?

Ans : 

Differences between Objective-C Category and Extension


1. Factor : Source code
Categories provide a way to add methods to a class even if its source code is not available to you. ex: NSString
Extensions are only possible if the source code is available , because compiler compiles the extension & source code at same time.
2. Factor : Instance variable/Properties
Category : Not possible
Extensions : Possible
3. Factor : Accessibility to Inherited classes.
Category — All methods defined inside a category are also available to the inherited class
Extensions — All properties and methods defined inside a class extension are not even available to inherited class.
When to use : 
Use category when you need to want to add any methods to a class whose source code is not available to you OR you want to break down a class into several files depending on its functionality.
Use class extensions when you want to add some required methods to your class outside the main interface file. Also when you want to modify a publicly declared variable in the main interface file .


Difference between Objective-C category and Swift extension :

Mostly Objective-C category and Swift extension are same. 

Diff : 

In Objective-C category, Computed property/variable can not be declared.
In Swift extension, Computed property(not stored property) can be declared.


Difference between pod install and pod update

Ans : 

pod install

This is to be used the first time you want to retrieve the pods for the project, but also every time you edit your Podfile to add, update or remove a pod.

Every time the pod install command is run — and downloads and install new pods — it writes the version it has installed, for each pods, in the Podfile.lock file. This file keeps track of the installed version of each pod and locks those versions.
When you run pod install, it only resolves dependencies for pods that are not already listed in the Podfile.lock.
For pods listed in the Podfile.lock, it downloads the explicit version listed in the Podfile.lock without trying to check if a newer version is available
For pods not listed in the Podfile.lock yet, it searches for the version that matches what is described in the Podfile (like in pod 'MyPod', '~>1.2')

pod outdated

When you run pod outdated, CocoaPods will list all pods which have newer versions than the ones listed in the Podfile.lock (the versions currently installed for each pod). This means that if you run pod update PODNAME on those pods, they will be updated — as long as the new version still matches the restrictions like pod 'MyPod', '~>x.y' set in your Podfile.

pod update

When you run pod update PODNAME, CocoaPods will try to find an updated version of the pod PODNAME, without taking into account the version listed in Podfile.lock. It will update the pod to the latest version possible (as long as it matches the version restrictions in your Podfile).

If you run pod update with no pod name, CocoaPods will update every pod listed in your Podfile to the latest version possible.


How to cancel alamofire api request?

Ans:

You can cancel a single request as below:
1 - First get the request:
let request = Alamofire.SessionManager.default.request(path!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: createHeader()).responseJSON { response in
    switch response.result {
    case .success(let data):
        success(data as AnyObject?)
    case .failure(let error) :
        failure(error as NSError)
    }
}
2 - Then, in your viewDidDisappear, just call:
request.cancel()

You can cancel all requests as below:
Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
    sessionDataTask.forEach { $0.cancel() }
    uploadData.forEach { $0.cancel() }
    downloadData.forEach { $0.cancel() }
}

According to different alamofire and swift version, above code may change little bit.

Have you done battery optimization for gps or api calling?

Ans :

Energy Efficiency in location gathering environment, What can be done.
Stop Location Updates if Accuracy Doesn’t Match Expectations
If your app isn’t receiving updates with the expected level of accuracy, your app should examine the updates it is receiving and determine whether accuracy is improving or staying about the same over time. If accuracy isn’t improving, it’s possible that the desired level of accuracy simply isn’t available at the moment. In this case, stop location updates and try again later so your app doesn’t continuously cause location hardware to draw power.

Stop Location Services When You Aren’t Using Them

With the exception of navigation apps that offer turn-by-turn directions, most apps don’t need location services to be on all the time. Turn location services on only when they’re needed. Then, leave them on just long enough to get a location fix and turn them off again. Unless the user is in a moving vehicle, the current location shouldn’t change frequently enough to be an issue. You can always start location services again later if you need another update.

Reduce Accuracy of Standard Location Updates Whenever Possible

Standard location updates let you specify a degree of accuracy ranging from a few meters to a few kilometers by setting the desiredAccuracy property of the location manager object. Requesting higher accuracy than you need causes Core Location to power up additional hardware and waste power for unnecessary precision. Unless your app really needs to know the user’s position within a few meters, don’t set the accuracy level to best (kCLLocationAccuracyBest) or nearest ten meters (kCLLocationAccuracyNearestTenMeters). Also, be aware that Core Location typically provides more accurate data than you have requested. For example, when specifying an accuracy level of three kilometers (kCLLocationAccuracyThreeKilometers), you may receive accuracy within a hundred meters or so.
IMPORTANT
By default, standard location updates on iOS devices run with an accuracy level of best. Change these settings to match your app’s requirements. Otherwise, your app will unnecessarily waste energy.
Auto-Pause and Specify an Activity Type When Receiving Location Updates in the Background
Make sure the location manager object’s pausesLocationUpdatesAutomatically property is set to YES to help conserve power.Set the activityType property to let Core Location know what type of location activity your app is performing at a given time — for example, if your app is performing fitness tracking or automotive navigation

Defer Location Updates When Running in the Background

On devices with GPS hardware, you can let the location manager defer the delivery of location updates when your app is in the background. For example, a fitness app that tracks the user’s location on a hiking trail can defer updates until the user has moved a certain distance or a certain period of time has elapsed. Then, it can process the updates all at once. To defer updates, call the location manager object’s allowDeferredLocationUpdatesUntilTraveled:timeout:method and pass it a distance and time that may elapse before the next location update is received. This method is typically called in the locationManager:didUpdateLocations: delegate method in order to defer again, if appropriate, when a deferred location update is received. When a deferred location update is received, the locationManager:didFinishDeferredUpdatesWithError: delegate method is also called, and your app can use this as an opportunity to adjust behavior accordingly — such as increasing or decreasing the deferral distance and time — for the next update

Restrict Location Updates to Specific Regions or Locations

Some apps don’t need to receive continuously location updates, and just need to know when the user is within a certain distance of a location. For example, a grocery app may display new coupons whenever the user nears the store. There are several Core Location APIs that can keep your app informed.
NOTE
The monitoring techniques described below provide entry and exit notifications only. To determine the user’s actual location when a notification is received, you must call the requestLocation: or startUpdatingLocation: method of the location manager object. These monitoring techniques also require an authorization status of kCLAuthorizationStatusAuthorizedAlways.
Activity Types
  • CLActivityTypeOther
The location manager is being used for an unknown activity.
  • CLActivityTypeAutomotiveNavigation
The location manager is being used specifically during vehicular navigation to track location changes to the automobile. This activity might cause location updates to be paused only when the vehicle does not move for an extended period of time.
  • CLActivityTypeFitness
The location manager is being used to track any pedestrian-related activity. This activity might cause location updates to be paused only when the user does not move a significant distance over a period of time.
  • CLActivityTypeOtherNavigation
The location manager is being used to track movements for other types of vehicular navigation that are not automobile related. For example, you would use this to track navigation by boat, train, or plane. Do not use this type for pedestrian navigation tracking. This activity might cause location updates to be paused only when the vehicle does not move a significant distance over a period of time.
Visit Monitoring
Visit monitoring allows an app to receive entry and exit notifications for specific locations the user visits frequently or for long periods of time such as home, work, or a favorite coffee shop.
To begin monitoring for visits, assign a delegate to the location manager object and call itsstartMonitoringVisits method. Note that calling this method enables all visit updates in your app, not just ones for the current delegate. When enabled, visit events are delivered to the locationManager:didVisit:method of the delegate. If your app isn’t running when a visit event is delivered, your app is relaunched automatically. When visit location updates are no longer required, call stopMonitoringVisits

Register for Significant-Change Location Updates Only as a Last Resort

If GPS-level accuracy isn’t critical for your app, you don’t need continuous tracking, and region or visit monitoring isn’t more appropriate for your app, you can use the significant-change location service instead of the standard one.
IMPORTANT
Region and visit monitoring are sufficient for most use cases and should always be considered before significant-change location updates. In the event significant-change location updates are needed, keep in mind the following, which can actually result in higher energy use if not employed effectively:
  • > Significant-change location updates wake the system and your app once every 15 minutes, at minimum, even if no location changes have occurred.
  • > Significant-change location updates run continuously, around the clock, until you stop them.
To start significant-change location updates, call the startMonitoringSignificantLocationChanges method of the location manager object. When you’re done, call stopMonitoringSignificantLocationChanges .