Python Forum
change normal insertionsort into 2 dimension insertionsort
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
change normal insertionsort into 2 dimension insertionsort
#1
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
Reply
#2
@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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to increase speed of access element in 2 dimension array? Diver 6 6,090 Nov-03-2016, 03:42 AM
Last Post: Diver

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020