0

我想将以下 JAVA 代码转换为 python(我是 Python 的初学者)

public void selectionSort(int[] arr) {
      int i, j, minIndex, tmp;
      int n = arr.length;
      for (i = 0; i < n - 1; i++) {
            minIndex = i;
            for (j = i + 1; j < n; j++)
                  if (arr[j] < arr[minIndex])
                        minIndex = j;
            if (minIndex != i) {
                  tmp = arr[i];
                  arr[i] = arr[minIndex];
                  arr[minIndex] = tmp;
            }
      }
}

这是我写的,但它不起作用,我无法弄清楚我做错了什么

A = [86, 2,4 ,5, 6122, 87]

def selectionSort(a):
    n = len(a)
    print ("n = ", n)
    for i in range (0, n-1):
        minIndex = i
        j = i+1
        for j in range (0, n):
            if(a[j] < a[minIndex]):
                minIndex = j
        if minIndex != i:
            tmp = a[i]
            a[i] = a[minIndex]
            a[minIndex] = tmp



selectionSort(A)
print(A)

请帮我理解为什么

4

3 回答 3

2

改变两行

j = i+1
for j in range (0, n):

for j in range (i+1, n):

匹配

for (j = i + 1; j < n; j++)

其他挑剔

在 python 中交换被优雅地完成为

a[i], a[minIndex] = a[minIndex], a[i]

和整个街区

    minIndex = i
    for j in range (i+1, n):
        if(a[j] < a[minIndex]):
            minIndex = j
    if minIndex != i:
        a[i], a[minIndex] = a[minIndex], a[i]

可以重构为

    minIndex = min(range(i,n), key = partial(getitem, a))
    a[i], a[minIndex] = a[minIndex], a[i]

前提是您从 functools 导入 partial从 operator导入 getitem

from functools import partial
from operator import getitem

所以你的最终版本看起来像

from functools import partial
from operator import getitem
def selectionSort(a):
    n = len(a)
    for i in range (n-1):
        minIndex = min(range(i,n), key = partial(getitem, a))
        a[i], a[minIndex] = a[minIndex], a[i]

最后看到哪个会让你想知道将 Java 代码转换为 Python 作为练习是否确实是学习 Python 的好方法

于 2013-03-01T17:58:32.837 回答
0
for j in range (0, n)

与使用 i+1 开始的 Java 不同。

实现选择排序的更 Pythonic 方式可能如下所示:

A = [86, 2,4 ,5, 6122, 87]
def selectionSort(a):
    # Go through all positions except the last one 
    # (that one will automatically be correct)
    for index in range(len(a)-1):
        value = a[index]
        # enumerate all (index, value) pairs from the rest of the list 
        # and take the pair with the smallest value
        min_subindex, min_value = min(enumerate(a[index+1:]), key=lambda x: x[1])
        if min_value < value:
            a[index] = min_value
            a[min_subindex + index + 1] = value

selectionSort(A)
print(A) # [2, 4, 5, 86, 87, 6122]
于 2013-03-01T17:58:27.910 回答
0

问题:

  1. 当你这样做j in range(0, n-1)时,它将在0而不是开始循环i+1

利用

for j in range(i+1, n-1)

工作代码:

A = [86, 2,4 ,5, 6122, 87]

def selectionSort(a):
    n = len(a)
    print ("n = ", n)
    for i in range (0, n-1):
        minIndex = i
        for j in range (i+1, n):
            if(a[j] < a[minIndex]):
                minIndex = j

        if minIndex != i:
            a[i], a[minIndex] = a[minIndex], a[i]

selectionSort(A)
print(A)
于 2013-03-01T17:59:16.970 回答