Python Forum
change normal insertionsort into 2 dimension insertionsort - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: change normal insertionsort into 2 dimension insertionsort (/thread-25339.html)



change normal insertionsort into 2 dimension insertionsort - dezed - Mar-27-2020

excuse me, i wanna ask.
how to change this code into 2Dimension insertionsort code?
my teacher said it only replace 1 line code

def insertionSort2D(arr):

    for i in range(1, len(arr)):
        key = arr[i]
        j=i-1
        while j>=0 and key<arr[j][0]:
            arr[j+1]=arr[j]
            j=j-1
        arr[j+1]=key
    print(arr)
this is not an insertionsort 2Dimension code.
i have to change it into 2dimension insertionsort code


RE: change normal insertionsort into 2 dimension insertionsort - buran - Mar-27-2020

@DeaD_EyE, I've soft deleted your post because it provides solution to a no-effort post in the homework section of the forum
https://python-forum.io/misc.php?action=help&hid=52

You may provide guidance, but don't give full solution


RE: change normal insertionsort into 2 dimension insertionsort - DeaD_EyE - Mar-27-2020

No problem.

Hints:
- iterate over the first dimension, which requires an additional loop on the top
- use the sub element, which is the 2nd dimension, to sort it inline with your algorithm
- key<arr[j][0] is wrong. Remove the [0] and think what this does. Exception: TypeError object is not subscriptable
- you're modifying the original data, which is bad, you could use copy.deepcopy to prevent the change of the original arr
- you should return the sorted 2D-array and not printing them in your function