2013-11-14 38 views
-1

我需要問用戶插入進程數量,進程ID和等待時間 然後我必須根據進程優先級進行排序,比較和打印 我是新的C,I無法弄清楚如何做到這一點 任何幫助預先感謝 由於*/從Struct中的排序,比較和顯示C

struct Process { 
    int Id; 
    int Prio; 
    int Time; 
}; 

struct Process process[100]; 


void init() { 
    printf("Enter number of processes:\n "); 
    scanf("%d",&n); 
    while(n<3) { 
    printf("Number has to be grater than 2\n"); 
    scanf("%d",&n); 
    } 

    for (int x=0; x<n; x++) { 
    printf("Process %d ID:\n ", x+1); 
    scanf("%d",&process[x].Id); 
    printf("Process %d priority:\n ", x+1); 
    scanf("%d",&process[x].Prio); 
    printf("Process %d time:\n ", x+1); 
    scanf("%d",&process[x].Time); 
    } 
} 

void priority() { 
    for (int x=0; x<n; x++) { 
    printf("%d",process[x].Id); 
    printf("  %d",process[x].Prio); 
    printf("   %d\n\n",process[x].Time); 
    } 
} 

void line(int dashes) { 
    for(int x=1;x<dashes;x++) { 
    printf("-"); 
    } 
} 

void display() { 
    printf("\n"); 
    printf("      PROCESS SCHEDULING\n"); 
    line(90); 
    printf("\n"); 
    printf("ID"); 
    printf(" PRIORITY"); 
    printf(" WAITING TIME"); 
    line(90); 
    printf("\n\n"); 
} 
int main() { 
    init(); 
    display(); 
    priority(); 
    return 0; 
} 
+0

如果我理解你的問題,你需要根據優先級對進程進行排序,只需應用任何排序算法並通過process.priority進行比較即可。你的麻煩究竟是什麼? Sintax? – IssamTP

+0

這是一項任務嗎?你正在關注哪個教程?你有沒有試過編譯這段代碼(變量「n」在哪裏)?哪個編譯器?哪個操作系統是這個? – x29a

+0

這是一個作業IssamTP。這個想法是我不知道要應用的算法/ sintax。 – escuk

回答

0

對於排序,你可以應用任何排序算法(冒泡排序,插入排序,堆排序..),但比較時相鄰元素,比較它們的優先級。類似於

if(process[index1].Prio < process[index2].Prio) 
0

這是BubbleSort的一個實現,它是一種用於排序的基本算法。這不是你能找到的最好的,但它是最容易理解的。參考here

void SortProcesses() 
{ 
    int right_bound = n - 1; /* Assuming you've declared n as number of processes inputed. */ 
    Process swap; 

    while(right_bound > 0) 
    { 
    for(int i = 0; i < right_bound; i++) 
    { 
     if(process[i].Prio > process[i + 1].Prio) 
     { 
     swap.Id = process[i+1].Id; 
     swap.Prio = process[i+1].Prio; 
     swap.Time = process[i+1].Time; 
     process[i+1].Id = process[i].Id; 
     // ... idem for Prio and Time; 
     process[i].Id = swap.Id; 
     // ... idem for Prio and Time 
     right_bound--; 
     } 
    } 
    } 
} 
+0

非常感謝大家。我用另一個for循環代替While循環。 – escuk

+0

還有更多的方法可以做同樣的事情。 – IssamTP