对数组进行冒泡排序所需的最小交换次数是多少?

时间:2016-09-01 12:35:57

标签: python algorithm sorting

我正在尝试解决Hackerrank问题New Year Chaos

enter image description here

可以在页面上找到进一步的说明。例如,将“已交换”队列表示为q,如果q = [2, 1, 5, 3, 4],则所需的互换次数为3:

enter image description here

根据https://www.quora.com/How-can-I-efficiently-compute-the-number-of-swaps-required-by-slow-sorting-methods-like-insertion-sort-and-bubble-sort-to-sort-a-given-array的第一个答案,冒泡排序所需的交换次数等于数组中的倒置次数。我尝试使用以下Hackerrank提交来测试这个:

#!/bin/python

import sys


T = int(raw_input().strip())
for a0 in xrange(T):
    n = int(raw_input().strip())
    q = map(int,raw_input().strip().split(' '))
    # your code goes here
    diff = [x - y for x, y in zip(q, range(1,n+1))]
    if any([abs(el) > 2 for el in diff]):
        print "Too chaotic"
    else:
        all_pairs = [(q[i], q[j]) for i in range(n) for j in range(i+1, n)]
        inversions = [pair[0] > pair[1] for pair in all_pairs]
        print inversions.count(True)

以下是本地运行的代码版本:

n = 5
q = [2, 1, 5, 3, 4]

diff = [x - y for x, y in zip(q, range(1,n+1))]
if any([abs(el) > 2 for el in diff]):
    print "Too chaotic"
else:
    all_pairs = [(q[i], q[j]) for i in range(n) for j in range(i+1, n)]
    inversion_or_not = [pair[0] > pair[1] for pair in all_pairs]
    print inversion_or_not.count(True)

对于给定的测试用例,脚本正确打印数字3.但是,对于所有其他“隐藏”测试用例,它给出了错误的答案:

enter image description here

我还尝试了一个实现冒泡排序的提交:

#!/bin/python

import sys

def swaps_bubble_sort(q):
    q = list(q)         # Make a shallow copy
    swaps = 0
    swapped = True
    while swapped:
        swapped = False
        for i in range(n-1):
            if q[i] > q[i+1]:
                q[i], q[i+1] = q[i+1], q[i]
                swaps += 1
                swapped = True
    return swaps

T = int(raw_input().strip())
for a0 in xrange(T):
    n = int(raw_input().strip())
    q = map(int,raw_input().strip().split(' '))
    # your code goes here
    diff = [x - y for x, y in zip(q, range(1,n+1))]
    if any([abs(el) > 2 for el in diff]):
        print "Too chaotic"
    else:
        print swaps_bubble_sort(q)

但结果相同(失败)。交换的最小数量是否不等于反转次数或通过冒泡排序获得的数量?

3 个答案:

答案 0 :(得分:1)

您只需计算冒泡排序所需的掉期数量。这是我的代码被接受。

T = input()
for test in range(T):
    n = input()
    l = map(int, raw_input().split())
    for i,x in enumerate(l):
        if x-(i+1) > 2:
            print "Too chaotic"
            break
    else:
        counter = 0
        while 1:
            flag = True
            for i in range(len(l)-1):
                if l[i] > l[i+1]:
                    l[i],l[i+1] = l[i+1],l[i]
                    counter += 1
                    flag = False
            if flag:
                break
        print counter

在您的第一个代码中,您的方法是O(n^2),这不适合n = 10^5。在这一行

all_pairs = [(q[i], q[j]) for i in range(n) for j in range(i+1, n)]

您正试图将10^10元组存储在RAM中。

你的第二个代码的问题是你正在使用diff的abs元素来确保数组不是混乱的。然而,一个人只能通过贿赂到达终点,并且不违反规则。所以你必须确保一个人不会出现两个以上的位置,而不是相反。

答案 1 :(得分:0)

Swift 4版本:

func minimumBribes(queue: [Int]) -> Int? {

  for (index, value) in queue.enumerated() {
     if value - (index + 1) > 2 { // `+ 1` needed because index starts from `0`, not from `1`.
        return nil
     }
  }
  var counter = 0
  var queue = queue // Just a mutable copy of input value.
  while true {
     var isSorted = true
     for i in 0 ..< queue.count - 1 {
        if queue[i] > queue[i + 1] {
           queue.swapAt(i, i + 1)
           counter += 1
           isSorted = false
        }
     }
     if isSorted {
        break
     }
  }
  return counter
}

// Complete the minimumBribes function below.
func minimumBribes(q: [Int]) -> Void {

    if let value = minimumBribes(queue: q) {
        print("\(value)")
    } else {
        print("Too chaotic")
    }

}

答案 2 :(得分:0)

干净的python解决方案:

{
  "lorem": "ipsum",
  "dolor":/* inline comment */ "sit amet",
  "consectetur": "adipiscing",
/*
multi
line
comment
*/  
  "Pellentesque": "ultrices",
//single line comment  
  "lectus": "nec",
  "elit": "dictum",
  "url": "http://example.com"
}