8
I have developed the following serial code to perform the Odd-Even Sort sorting, which first sorts even/odd and then odd/even.
import time
def oddevenSort(x):
sorted = False
while not sorted:
sorted = True
#ordena indices par/impar
for i in range(0, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
#ordena indices impar/par
for i in range(1, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
print(x)
return x
tic = time.time()
oddevenSort([4,3,2,1,3,6,9,1,2,3,54,76,98,12,333,331,33,1,7,9])
toc = time.time()
print("tempo gasto para processar = " + str(toc-tic)+"s")
Now I need to create for this same sorting algorithm a parallel code in python to be able to calculate the Speedup (gain of time between running serial code VS parallel code).
To first approach what I was having was to create a thread for even/odd ordering and another for odd/even ordering, but I can’t understand what the behavior of this code is going to be like. In my view this algorithm should run all the even/odd part and then in SEQUENCE the odd/even part. Thus, I would have to synchronize thread 1 and thread 2, preventing code from occurring in parallel.
Example thread 1 (even/odd):
for i in range(0, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
Example thread 2 (odd/even):
for i in range(1, len(x)-1, 2):
if x[i] > x[i+1]:
x[i], x[i+1] = x[i+1], x[i]
sorted = False
To second approach would parallelize EVEN/ODD ordering (type thread 1 takes the first half of the numbers and sorts while thread 2 takes the second half and sorts). The same thing for the ODD/EVEN part (thread 3 sorts half and thread 4 sorts the other half).
Example:
Vetor completo: (9,8,7,6,5,4,3,2,1,0)
Thread 1 sorts: 9,8,7,6,5
Thread 2 sorts: 4,3,2,1,0
Expected result thread 1: 5.6.7.8.9
Expected thread 2 result: 0.1.2.3.4
Expected result of the final ordering: 0,1,2,3,4,5,6,7,8,9
Approach 3? Suggestions? If there is no other more efficient way, would you like help to implement one of the two suggestions.
It looks a lot like Bubble Sort, only it avoids the excess of rabbits and turtles. More parallelizable than the Sort cocktail... I believe that strategy 2 disfigures this ordering, and strategy 1 makes it difficult to synchronize all these sorts...
– Jefferson Quesado
@Jeffersonquesado could elaborate a little more? I could not fully understand his answer.
– lucasgvarela
It was just a comment. Crafting better: part 1) new ordering for me, looks like Bubble Sort, part 2) strategy 3 is the correct one, not the previous ones. Speaking of strategy 3, I already have an idea of how.
– Jefferson Quesado
Hmmmm, well, actually, I don’t know what it would be like in Python, but I have a general idea of what it would be like
– Jefferson Quesado
I’m looking for someone here to help with the Python part, meanwhile I’ll write the general scheme
– Jefferson Quesado