How to find the median of elements in an array in Kotlin
How to find the median of elements in an array in Kotlin.
Here's a detailed step-by-step tutorial on how to find the median of elements in an array using Kotlin:
Step 1: Declare an array
Start by declaring an array of numbers for which you want to find the median. For example, let's say we have an array of integers called "numbers":
val numbers = arrayOf(5, 2, 9, 1, 7, 3)
Step 2: Sort the array
To find the median, we need to sort the array in ascending order. Kotlin provides a built-in function called "sorted()" that can be used to sort the array. We will assign the sorted array to a new variable called "sortedNumbers":
val sortedNumbers = numbers.sorted()
Step 3: Find the median
The median is the middle element in the sorted array. If the array has an odd number of elements, the median is the middle element itself. If the array has an even number of elements, the median is the average of the two middle elements.
To find the median, we can use the following logic:
val median: Double = if (sortedNumbers.size % 2 == 1) {
sortedNumbers[sortedNumbers.size / 2].toDouble()
} else {
(sortedNumbers[sortedNumbers.size / 2 - 1] + sortedNumbers[sortedNumbers.size / 2]) / 2.0
}
Let's break down the logic:
- If the size of the sorted array is odd (i.e.,
sortedNumbers.size % 2 == 1), we can directly access the middle element at indexsortedNumbers.size / 2and convert it to aDouble. - If the size of the sorted array is even, we need to find the average of the two middle elements. The two middle elements are at indices
sortedNumbers.size / 2 - 1andsortedNumbers.size / 2. We add them together and divide by 2.0 to get the average.
Step 4: Print the median
Finally, you can print the median to see the result:
println("The median is: $median")
Here's the complete code:
val numbers = arrayOf(5, 2, 9, 1, 7, 3)
val sortedNumbers = numbers.sorted()
val median: Double = if (sortedNumbers.size % 2 == 1) {
sortedNumbers[sortedNumbers.size / 2].toDouble()
} else {
(sortedNumbers[sortedNumbers.size / 2 - 1] + sortedNumbers[sortedNumbers.size / 2]) / 2.0
}
println("The median is: $median")
This will output:
The median is: 4.0
In this example, the median of the array [5, 2, 9, 1, 7, 3] is 4.0.