Sort lists without Sort

Asked

Viewed 244 times

1

I’m trying to solve an exercise, but I’m not getting any results yet. I’m new to language.

'''Define a merge function that does the following: Given two ordered lists L1 and L2, returns an ordered list of all L1 and L2 numbers.

The function should NOT use python’s Sort method.

Instead, do the following: * Create an I1 index for the L1 list and an I2 for L2 * Initialize I1 and I2 with 0 * Compare L1[I1] to L2[I2] and put the smaller of the two on the response list. If the lowest was L1[I1], increase I1. Otherwise, increase I2 * Thus, L1[I1] and L2[I2] are always the smallest elements of L1 and L2, and one of them is always the next to enter in response * Keep doing this until you add all the elements of L1 and L2 in response'''

I tried to do something like this below

def merge(lista1, lista2):
    i1 = 0
    i2 = 0
    resposta = []
    lista = lista1 + lista2
    for num in lista:
        if num < lista2[i2]:
            resposta.append(lista1[i1])
            i1 += 1
        else:
            resposta.append(lista2[i2])
            i2 += 1
    return resposta
  • 1

    https://answall.com/questions/252400/python-order-lists-sem-o-sort See if this helps...

  • The name of this is balance line, join two already ordered lists.

1 answer

1


The name of this algorithm is 'Balance Line', it was something usually implemented in the times of COBOL, where the data came from ordered magnetic tapes, I believe.

#!/usr/bin/env python3

def merge(lista1, lista2):
        i1 = 0
        i2 = 0
        resposta = []
        while True:
                if i1 < len(lista1) and i2 < len(lista2):
                        if lista1[i1] <= lista2[i2]:
                                resposta.append(lista1[i1])
                                i1 += 1
                        else:
                                resposta.append(lista2[i2])
                                i2 += 1
                elif i1 < len(lista1):
                        # lista2 esgotada
                        resposta.append(lista1[i1])
                        i1 += 1
                elif i2 < len(lista2):
                        # lista1 esgotada
                        resposta.append(lista2[i2])
                        i2 += 1
                else:
                        # Ambas listas esgotadas
                        break
        return resposta

print(merge([1, 3, 5, 7, 9, 11], [1, 2, 3, 4, 6]))
  • Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.