Andrew Andrew - 6 months ago 22
Python Question

Bad Selection Sort in Python

I have a problem with a simple sort of a multidimensional array.

The Python code is:

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


The problem is that the output of the file is:
(The sorted matrix should be at the end of the file, like this)
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


So, it's not like the best sort in the world..
I think the problem is in the SelectionSort.py file, I kind of messed up the "length[i]" and the "i" variables. I am a beginner, any help is appreciated!
Thank you!

Answer

sort method has a small bug in it, it's comparing loop counter j against minimum value. If you make the following change it will fix the issue:

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
Comments