關於程式排序的問題 (distributed sorting)?
有10個獨立的程序P1~P10,各自取10個 1~1000之間的隨機整數
各個程序只能跟隔壁的交換數字 (P4只能跟 P3, P5換這樣)
請問要如何把全部100個數字按照順序排好?
在什麼條件下能判定說排序已經完成?
謝謝
回答 (3)
先找出P1~P10各自的最大值和最小值,這樣就可以決定有沒有需要和隔壁交換數字。
當P1~P10都不需要交換數字時,再各自排序自己的10個數字,排序完成就結束。
for each Pi:
A) allocate data[10] and assign random numbers
B) sort data[10] in ascending order
C) send the data[0] to the left, except for the p1
D) send the data[9] to the right, except for the p10
E) at P1..P9, receive the data R from the right
F) at P2..P10, receive the data L from the left
G) at P10,
if the L <= data[0], send signal (DONE) to the left,
else replace data[0] by L and send signal (NOT DONE) to the left
H) at P1,
if R >= data[9], send signal(DONE) to the right,
else replace data[9] by R and send signal(NOT DONE) to the right
I) at P2..P9, receive signal Sr from the right.
If L > data[0] then set Sr = NOT DONE, copy L to data[0]
receive signal Sl from the left
if R < data[9] then set Sl = NOT DONE, copy R to data[9]
send Sr to the left, send Sl to the right
J) if P5 have Sr == DONE and Sl == DONE, the the sorting is done.
K) go to B;
// pseudo code
int pid = 1..10; // process ID
int data[10]; // data array with random number
int L, R; // data received from left and right
bool sigL, sigR; // signal received from left and right
bool clean; // locally clean
// init
sigL = sirR = false;
if(id == 1) sigL = true;
else if(id == 10) sigR = true;
// assign random number to data[]
for(; !clean || !sigL || !sigR; ){
sort(data);
if(id != 1) send_left(data[0]);
if(id != 10) send_right(data[9]);
if((id != 1) L = receive_left();
if(id != 10) R = receive_right();
clean = true;
if(id != 1) { if(L > data[0]) { data[0] = L; clean = sigR = false;}}
if(id != 10) [if(R < data[9]) { data[9] = R; clean = sigL = false;}}
if(id != 1) signal_left(sigR);
if(id != 10) signal_right(sigL);
if(id != 1) sigL = recSigLeft();
if(id !=10) sigR = recSigRight();
}
最簡單的方法,每一組鎖定一組數字,就是p1鎖定1~100,p2鎖定2~200,然後每組自行檢查不屬於自己的數字,然後執行一次下列程序。
總排異數=1000;總排異數不等於0則迴圈
由P1到p10執行下列程序
把第一個需排異數字(無則跳過)向正確的方向交換一個方向正確的數字(無則取第一個本組數字)
檢查本組需排異數字數量並設為變數,把前項加到總排異數
Return
如總排異數=0,判斷為完成
收錄日期: 2021-04-25 13:53:52
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20170425032947AAOKfYw
檢視 Wayback Machine 備份