简体   繁体   English

插入排序高级分析算法

[英]algorithem for Insertion Sort Advanced Analysis

Insertion Sort is a simple sorting technique which was covered in previous challenges.插入排序是一种简单的排序技术,在之前的挑战中已经介绍过。 Sometimes, arrays may be too large for us to wait around for insertion sort to finish.有时,数组可能太大,我们无法等待插入排序完成。 Is there some other way we can calculate the number of shifts an insertion sort performs when sorting an array?有没有其他方法可以计算插入排序在对数组进行排序时执行的移位数?

If is the number of elements over which the element of the array has to shift, then the total number of shifts will be... +.如果 是数组元素必须移位的元素数,则移位总数将为... +。

Example例子

Array       Shifts
[4,3,2,1]   
[3,4,2,1]   1
[2,3,4,1]   2
[1,2,3,4]   3

Total shifts = 1 + 2 + 3 = 6

Function description功能说明

Complete the insertionSort function in the editor below.在下面的编辑器中完成insertionSort功能。

insertionSort has the following parameter(s): insertionSort 具有以下参数:

int arr[n]: an array of integers Returns int arr[n]:整数数组 返回

  • int: the number of shifts required to sort the array int:对数组进行排序所需的移位数

Input Format输入格式

The first line contains a single integer, the number of queries to perform.第一行包含一个整数,即要执行的查询数。

The following pairs of lines are as follows:下面几对线如下:

The first line contains an integer, the length of.第一行包含一个整数,长度。 The second line contains space-separated integers.第二行包含以空格分隔的整数。 Constraints约束条件

Sample Input样本输入

2  
5  
1 1 1 2 2  
5  
2 1 3 1 2

Sample Output示例输出

0  
4   

Explanation解释

The first query is already sorted, so there is no need to shift any elements.第一个查询已经排序,所以不需要移动任何元素。 In the second case, it will proceed in the following way.在第二种情况下,它将按以下方式进行。

Array: 2 1 3 1 2 -> 1 2 3 1 2 -> 1 1 2 3 2 -> 1 1 2 2 3
Moves:   -        1       -    2         -  1            = 4

looking to solve this algorithem寻找解决这个算法

Python program to solve this algorithem:解决此算法的 Python 程序:

import math
import os
import random
import re
import sys

def insertionSort1(n, arr):
    target = arr[-1]
    idx = n-2

    while (target < arr[idx]) and (idx >= 0):
        arr[idx+1] = arr[idx]
        print(*arr)
        idx -= 1

    arr[idx+1] = target
    print(*arr)

if __name__ == '__main__':
    n = int(input().strip())

    arr = list(map(int, input().rstrip().split()))

    insertionSort1(n, arr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM