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