Write a program that counts the number of required shifts to sort the numbers in the descending order using insertion sort.
By shift, we mean the case when we move elements in the sorted part to insert a new element. Another case is when a new element is added to the end of the sorted part without any shifts.
The following picture shows both the cases. We do not need any shifts to add 21 to the sorted part, but we must perform a shift to insert 24 in the sorted part.
Do not count the number of exchanges. You should count only the number of required shifts. An iteration may contain no more than one shift.
Input data format
The first line contains the number of elements. The second line consists of elements separated by space.
Output data format
Output one integer number, which is the number of required shifts.
Sample Input 1:
5
50 40 30 10 20
Sample Output 1:
1
Sample Input 2:
5
30 40 20 5 10
Sample Output 2:
2
Sample Input 3:
8
5 2 9 1 2 4 9 5
Sample Output 3:
5
import java.util.*;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int[] arr = new int[len];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
int swap = 0;
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (min >= arr[i]) {
min = arr[i];
} else {
swap++;
}
}
System.out.println(swap);
}
}
Insertion sort in Java The number of required shifts
原文:https://www.cnblogs.com/longlong6296/p/13508263.html