2016-05-30 54 views
1

我有一個簡單的多維數組排序問題。不良選擇排序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; 

MatriceSelectionSort.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」變量。我是初學者,任何幫助表示讚賞! 謝謝!

回答

0

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 
+0

棒極了!謝謝你,它像一個魅力! – Andrew