首页 > 编程语言 > 详细

Insertion sort in Java The number of required shifts

时间:2020-08-15 13:35:09      阅读:62      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!