0

I've written an implementation of the selection- and insertion-sortingalgorithms in PHP and wanted to translate them to Python as a test to compare the runtime.

As I'm relatively new to Python I'm wondering why this code doesn't work properly. It returns the array given in the function call.

Python Script:

def insertionSort(sort_array: list):
    for i in range(0, len(sort_array)-1, +1):
        for j in range (i+1, 0, -1):
            if sort_array[j-1] > sort_array[j]:
                temp = sort_array[j-1]
                sort_array[j-1] = sort_array[j]
                sort_array[j] = temp
    return sort_array

print(insertionSort([11, 2, 4, 8, 7, 3, 9]))

[11, 2, 4, 8, 7, 3, 9]

Process finished with exit code 0

PHP Script (working)

function insertionSort($sort_array){
    for ($i = 0; $i < count($sort_array); $i++){                         
      for ($j = $i + 1; $j > 0; $j--){                          
        if($sort_array[$j-1] > $sort_array[$j]){
          $temp = $sort_array[$j-1];
          $sort_array[$j-1] = $sort_array[$j];
          $sort_array[$j] = $temp;               
        }          
      } 
    }
    return $sort_array;
}

Thank you in advance. Any critic of my Python style is welcome.


Edit: Apparently it's a problem with my local system, as an online interpreter returns the correctly sorted array: https://repl.it/GULW

pguetschow
  • 5,176
  • 6
  • 32
  • 45
  • @linusg Quote:"It returns the array given in the function call." It basically doesn't sort the array. I guess the problem is caused by either the range and/or the de/incrementing – pguetschow Mar 14 '17 at 09:43
  • @linusg well..it seems to work on every online ide, see edit. But everything is correct or can I simplify anything? – pguetschow Mar 14 '17 at 09:50
  • @linusg Fedora 24 with PyCharm using 3.5. Problem is PyCharm, call via console works. @ Downvoter: Wow, why the downvote? – pguetschow Mar 14 '17 at 09:53
  • Np, was just curious why ppl on SO downvote w/o a comment. But yeah, seems to be an IDE specific problem – pguetschow Mar 14 '17 at 09:55
  • @linusg Strange, rebooted ans same problem. Guess I have to check all configs – pguetschow Mar 14 '17 at 09:59

0 Answers0