The source code to sort an array in ascending order using insertion sort is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to sort an array in
// ascending order using insertion sort
object Sample {
def main(args: Array[String]) {
var IntArray = Array(11, 15, 12, 14, 13)
var i: Int = 0
var j: Int = 0
var item: Int = 0
// Sort array using insertion sort in ascending order.
i = 1
while (i < 5) {
item = IntArray(i)
j = i - 1
while (j >= 0 && IntArray(j) > item) {
IntArray(j + 1) = IntArray(j);
j = j - 1;
}
IntArray(j + 1) = item;
i = i + 1
}
i = 0;
println("Sorted Array in ascending order: ");
while (i < 5) {
printf("%d ", IntArray(i));
i = i + 1;
}
println()
}
}
Output:
Sorted Array in ascending order:
11 12 13 14 15
Explanation:
In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.
In the main() function, we created an integer array IntArray with 5 elements. Then we sorted the IntArray in ascending order using insertion sort. After the sorting process, we printed the sorted array on the console screen.
Program/Source Code:
The source code to sort an array in ascending order using insertion sort is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Output:
Explanation:
In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.
In the main() function, we created an integer array IntArray with 5 elements. Then we sorted the IntArray in ascending order using insertion sort. After the sorting process, we printed the sorted array on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer