-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortingTask.swift
More file actions
50 lines (40 loc) · 1.9 KB
/
sortingTask.swift
File metadata and controls
50 lines (40 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* sort the elements in a array and calculate sum until condition become false.
conditions : first get a index position from user then calcalute total like array[index] - array[index - 1] .this total calculation method goes on until (index > 0).after that add all the elements.
input format : array
index position
output : sorted array
sum of values.
*/
import Foundation
var arrayOfElements = [1,4,3,2,5]
func doSelectionSortWithMinimumSwap(for arrayOfElements:[Int]) {
var arrayOfElements = arrayOfElements
var temporaryIndexOfMinimumValue = -1 , swapCount = 0
for eachIteration in 0..<arrayOfElements.count - 1 {
temporaryIndexOfMinimumValue = eachIteration
for eachNumber in (eachIteration + 1)..<arrayOfElements.count {
if arrayOfElements[temporaryIndexOfMinimumValue] > arrayOfElements[eachNumber] {
temporaryIndexOfMinimumValue = eachNumber
}
}
if temporaryIndexOfMinimumValue != eachIteration {
arrayOfElements.swapAt(temporaryIndexOfMinimumValue,eachIteration)
swapCount += 1
}
}
print("SwapCount: \(swapCount)")
}
func calculateSumOfSubtractedValuesForSortedArray(until indexPosition : Int) -> Int {
var sumOfSubractionValues = 0, eachIteration = 0
while eachIteration != indexPosition {
sumOfSubractionValues += abs(arrayOfElements[eachIteration + 1] - arrayOfElements[eachIteration])
eachIteration += 1
}
return sumOfSubractionValues
}
doSelectionSortWithMinimumSwap(for: arrayOfElements)
print("Sorted Array: \(arrayOfElements)")
let indexPositionForSumOfSubraction = 4
if indexPositionForSumOfSubraction > 0 && indexPositionForSumOfSubraction < arrayOfElements.count {
print("sumOfSubractionValues : \(calculateSumOfSubtractedValuesForSortedArray(until :indexPositionForSumOfSubraction))")
}