How to sort an integer array based on a duplicate values count. here less number of duplicates should come first.
input [5, 2, 1, 2, 4, 4, 1, 1, 2, 3, 3, 6]
OutPut [5, 6, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1]
CodePudding user response:
This is actually really easy to do using the .sort/.sorted
function like this:
let output = input.sorted { i1, i2 in
i1 != i2
}
CodePudding user response:
let numbers = [5,2,1,2,4,4,1,1,2,3,3,6]
let sortedNumber = numbers.sorted()
print("Input: ",sortedNumber)
var dict = [Int: Int]()
for item in sortedNumber {
let isExist = dict.contains(where: {$0.key == item})
if !isExist {
dict[item] = 1
} else {
if let value = dict[item] {
dict[item] = value 1
}
}
}
var finalArray = [Int]()
let sortedArray = dict.sorted { (first, second) -> Bool in
return first.value < second.value
}
for d in sortedArray {
for _ in 1...d.value {
finalArray.append(d.key)
}
}
print("Output: ",finalArray)
Input: [1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6]
Output: [5, 6, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1]