我必須使用SRTN算法模擬進程調度器,並且在某個部分內部遇到問題。排序隊列
我有一個名爲'Process'的自定義類的隊列,我需要根據名爲'last_prediction'的字段對它進行排序。我的代碼大部分時間都在工作,但是如果您查看我的output的時間:19,就緒隊列中的輸出錯誤(應爲:1004(1.5)1002(2)1003(2))。
這裏是我的代碼:
int count = ReadyQueue.Count;
// Copy Queue into Vector
ArrayList temp = new ArrayList();
for (int i = 0; i < count; i++)
{
Process p = (Process)ReadyQueue.Dequeue();
temp.Add(p);
}
// Sort Vector
for (int i = 0; i < count; i++)
{
double min = ((Process)temp[i]).last_prediction;
for (int j=i+1; j<count; j++)
{
if (((Process)temp[j]).last_prediction < min)
{
min = ((Process)temp[j]).last_prediction;
Process dummy = (Process)temp[j];
temp[j] = temp[i];
temp[i] = dummy;
}
}
}
// Copy Vector back into Queue
for (int i = 0; i < count; i++)
{
Process p = (Process)temp[i];
ReadyQueue.Enqueue(p);
}
編輯:好吧,我嘗試使用ICompare,類似於你所付出的hughdbrown.Now我得到一個不同的錯誤:
public class Process
{
public int process_id;
public int arrival_time;
public int total_time;
public int avg_burst;
public int actual_burst;
public int last_burst; // SRTN
public double last_prediction; // SRTN
public int io_delay;
public int context_switch_delay;
public class ProcessSort : IComparer
{
public int Compare(object x, object y)
{
var a = x as Process;
var b = y as Process;
double aNum = a.last_prediction;
double bNum = b.last_prediction;
return Compare(aNum, bNum);
}
}
}
這是錯誤我現在得到:
Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> System.NullReferenceException: Object reference not set to an instance of an object.
它不會停止成爲一個隊列,一旦你排序嗎?它只是成爲另一個列表。 – 2010-10-16 03:17:04
A1(B1)A2(B2)A3(B3)您是否想根據B值對其進行排序,然後根據它們的A值對具有相同B值的那些進行排序? – blizpasta 2010-10-16 03:37:31
不完全。我需要它,所以進程停留在它的位置,如果它前面的值是等值的 – 2010-10-16 04:16:37