Python 中的错误选择排序

Bad Selection Sort in Python

我对多维数组的简单排序有疑问。

Python代码是:

SelectionSort.py

class SelectionSort(object):

    @staticmethod
    def sort(list):
        for i in range(0, len(list)):
            min = i;
            for j in range (i+1, len(list)):
                if j < list[min]:
                    min = j;
            tmp = list[min];
            list[min] = list[i];
            list[i] = tmp;
        return list;

矩阵SelectionSort.py

import sys;
import traceback;
import re;
from SelectionSort import SelectionSort;

class MatriceSelectionSort(object):

    def run(self):
        if len(sys.argv) < 2:
            print("Missing fileName arg! Examplu de rulare: python MatriceSelectionSort C:\wsmt\matrice.txt\n");
            sys.exit(1);
        fileName = sys.argv[1];
        try:
            matrix = self.readMatrix(fileName);
            for row in matrix:
                SelectionSort.sort(row);
            self.writeResult(fileName, matrix);
        except Exception as e:
            print("Nu pot citi/parsa fisierul\n");
            traceback.print_exc(); 


    def readMatrix(self, fileName):
        matrix = [];
        with open(fileName, "r") as file:
            for line in file:
                row = [];
                tokens = re.split("\s+", line);
                for token in tokens:
                    if token:
                        row.append(int(token));
                matrix.append(row);
        return matrix;   


    def writeResult(self, fileName, matrix):
        with open(fileName, "a") as file:
            file.write("\n\n"); # python will translate \n to os.linesep
            for row in matrix:
                for item in row:
                    file.write(str(item) + " ");
                file.write("\n");


if __name__ == '__main__':
    MatriceSelectionSort().run();

Matrice.txt

7 3 1 9 4
2 1 10 4 9
12 4 23

问题是文件的输出是: (排序后的矩阵应该在文件的末尾,像这样) Matrice.txt

7 3 1 9 4
2 1 10 4 9
12 4 23

1 4 3 7 9 
1 2 4 9 10 
23 12 4 

所以,这不是世界上最好的类型.. 我认为问题出在 SelectionSort.py 文件中,我搞砸了 "length[i]" 和 "i" 变量。我是初学者,任何帮助表示赞赏! 谢谢!

sort 方法有一个小错误,它将循环计数器 j 与最小值进行比较。如果您进行以下更改,它将解决问题:

def sort(list):
    for i in range(0, len(list)):
        min = i;
        for j in range (i+1, len(list)):
            if list[j] < list[min]: # Instead of if j < list[min]:
                min = j
        tmp = list[min]
        list[min] = list[i]
        list[i] = tmp
    return list