create a java program that input 5 animals and sort it in descending order by the use of insertion sort.
Answers
Explanation:
Selection Sort is a sorting algorithm that sorts data items into ascending or descending order. Sorting takes place through all the data items one-by-one while looking for either largest or smallest data values and making only one swap after finding either largest or smallest data values. Hence, this sorting algorithm is referred to as the selection sort because on each pass this algorithm selects either largest or smallest of the remaining unsorted data values and places them in the right order.
Code description
Concept of Selection Sort is simple. Now, array is imaginarily divided into two parts-sorted one and unsorted one. In beginning sorted part is empty, while unsorted one contains whole array. At every step, the algorithm finds minimal element in the unsorted part and adds it to the end of the sorted one. When unsorted part becomes empty, algorithm stops.
When algorithm sorts an array, it swaps first element of unsorted part with minimal element and then it is included to the sorted part. This implementation of selection sort in not stable. In case of linked list is sorted, and, instead of swaps, minimal element is linked to the unsorted part, selection sort is stable.
Let us see an example of sorting an array to make the idea of selection sort clearer.
Example
Sort the array {5, 1, 12, -5, 16, 2, 12, 14} using selection sort.