Answer to Question #253493 in Python for shishi

Question #253493

Write a program which takes as input a huge array of numbers. This array is

split into n sub-arrays and n threads apply a bubble sort on each of the n

sub-arrays. Lastly, another thread merges the n sorted sub-arrays into one

with the same size as the original array. Of course, the resulting array

should be sorted.


1
Expert's answer
2021-10-19T12:19:33-0400
import threading

def bubble_sort(lst):
    n = len(lst)
    for i in range(n):
        maxind = 0
        for j in range(1, n - i):
            if lst[j] > lst[maxind]:
                maxind = j
        lst[n - 1 - i], lst[maxind] = lst[maxind], lst[n - 1 - i]

def merge_lists(lst1, lst2):
    if len(lst2) > 0:
        k = 0
        ins_el = lst2.pop(0)
        while k < len(lst1):
            if ins_el < lst1[k]:
                lst1.insert(k, ins_el)
                ins_el = lst2.pop(0)
            if len(lst2) == 0:
                break
            k += 1
        lst1 += lst2

def merge_biglist(biglist):
    while len(biglist) > 1:
        m = 0
        while m < len(biglist) - 1:
            merge_lists(biglist[m], biglist[m + 1])
            del biglist[m + 1]
            m += 1

def sort_biglist(biglist):
    for sublist in biglist:
        t = threading.Thread(target=bubble_sort, args=([sublist]))
        t.start()
        t.join()

    t = threading.Thread(target=merge_biglist, args=([biglist]))
    t.start()
    t.join()

    biglist += biglist.pop(0)

# sample data:
biglist = [[122, 263, 778, 402, 658, 886, 90, 608, 867, 945], [433, 762, 778, 434, 135, 235, 268, 687, 738, 853], [51, 294, 132, 291, 241, 38, 492, 406, 672, 519], [301, 222, 981, 782, 882, 387, 849, 371, 964, 381], [921, 641, 850, 68, 459, 699, 177, 570, 540, 647], [27, 717, 664, 769, 656, 527, 272, 975, 537, 97], [703, 128, 266, 933, 202, 15, 301, 512, 335, 889], [442, 890, 885, 278, 474, 762, 413, 606, 227, 411], [869, 774, 671, 774, 378, 154, 693, 36, 950, 321], [191, 204, 239, 776, 833, 987, 414, 397, 99, 374]]
sort_biglist(biglist)
print(biglist)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS