The source code to sort an array in ascending order using insertion sort is given below. The given program is compiled and executed successfully.
# Ruby program to sort an array in ascending order
# using insertion Sort
arr = [12,69,49,87,68];
i = 1;
while (i < 5)
item = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > item)
arr[j + 1] = arr[j];
j = j - 1;
end
arr[j + 1] = item;
i = i + 1;
end
print "Sorted Array in ascending order: \n";
i=0;
while(i<5)
print arr[i]," ";
i=i+1;
end
Output:
Sorted Array in ascending order:
12 49 68 69 87
Explanation:
In the above program, we created an array of integer elements. Then we sorted the array elements in ascending order using the insertion sort mechanism. After that, we printed the sorted array.
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 successfully.
Output:
Explanation:
In the above program, we created an array of integer elements. Then we sorted the array elements in ascending order using the insertion sort mechanism. After that, we printed the sorted array.
need an explanation for this answer? contact us directly to get an explanation for this answer