Techno Blender
Digitally Yours.

Sorting with Tapes : Balanced Merge

0 45


  

  

  

def balanced_merge_sort(data, num_tapes):

  

    

    tapes = [[] for _ in range(num_tapes)]

  

    

    for i, x in enumerate(data):

  

        tapes[i % num_tapes].append(x)

  

    

    for tape in tapes:

        tape.sort()

  

    

    

    while len(tapes) > 1:

  

        new_tapes = []

        for i in range(0, len(tapes), 2):

            tape1 = tapes[i]

            tape2 = tapes[i + 1] if i + 1 < len(tapes) else None

            new_tapes.append(merge(tape1, tape2))

        tapes = new_tapes

  

    

    return tapes[0]

  

  

def merge(tape1, tape2):

    if tape2 is None:

        return tape1

  

    

    

    output_tape = []

  

    i = j = 0

  

    

    while i < len(tape1) and j < len(tape2):

  

        if tape1[i] < tape2[j]:

            output_tape.append(tape1[i])

            i += 1

        else:

            output_tape.append(tape2[j])

            j += 1

    output_tape.extend(tape1[i:])

    output_tape.extend(tape2[j:])

    return output_tape

  

  

  

data = [5, 2, 4, 6, 1, 3]

  

sorted_data = balanced_merge_sort(data, 3)

  

print(sorted_data)


  

  

  

def balanced_merge_sort(data, num_tapes):

  

    

    tapes = [[] for _ in range(num_tapes)]

  

    

    for i, x in enumerate(data):

  

        tapes[i % num_tapes].append(x)

  

    

    for tape in tapes:

        tape.sort()

  

    

    

    while len(tapes) > 1:

  

        new_tapes = []

        for i in range(0, len(tapes), 2):

            tape1 = tapes[i]

            tape2 = tapes[i + 1] if i + 1 < len(tapes) else None

            new_tapes.append(merge(tape1, tape2))

        tapes = new_tapes

  

    

    return tapes[0]

  

  

def merge(tape1, tape2):

    if tape2 is None:

        return tape1

  

    

    

    output_tape = []

  

    i = j = 0

  

    

    while i < len(tape1) and j < len(tape2):

  

        if tape1[i] < tape2[j]:

            output_tape.append(tape1[i])

            i += 1

        else:

            output_tape.append(tape2[j])

            j += 1

    output_tape.extend(tape1[i:])

    output_tape.extend(tape2[j:])

    return output_tape

  

  

  

data = [5, 2, 4, 6, 1, 3]

  

sorted_data = balanced_merge_sort(data, 3)

  

print(sorted_data)

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment