Reputation:
for (int k = 0; k < proc.Count; k++){
for (int i = k + 1; i < proc.Count; i++){
if (proc[k].arrivalTime >= proc[i].arrivalTime && proc[k].priority >= proc[i].priority && proc[k].brust > proc[i].brust){
temp = proc[i];
proc[i] = proc[k];
proc[k] = temp;
}
}
}
Input
Process Arrival Brust Priority
P0 0 10 5
P1 1 3 1
P2 1 2 1
P3 5 1 5
P4 5 8 2
I want to sort these processes following these rules 1) If the process arrived alone it'll work no matter what. 2) If 2 processes arrived in the same time, we gonna check the priority if the first one has higher priority(lower number) it'll work first, and if they have the same priority we gonna let the one who has lower Brust work first.
There's problem with last 2 processes where's the problem?
P3 5 1 5
P4 5 8 2
process 4 should work because it has higher priority
Upvotes: 0
Views: 124
Reputation: 205579
You provided very clear explanation of the rules.
Now check this line
if (proc[k].arrivalTime >= proc[i].arrivalTime && proc[k].priority >= proc[i].priority && proc[k].brust > proc[i].brust)
Is it doing what the rules say? Definitely no. The direct translation of the rules would be something like this
if (proc[k].arrivalTime > proc[i].arrivalTime ||
(proc[k].arrivalTime == proc[i].arrivalTime &&
(proc[k].priority > proc[i].priority ||
(proc[k].priority == proc[i].priority && proc[k].brust > proc[i].brust))))
Better and more readable would be
int compare = proc[k].arrivalTime.CompareTo(proc[i].arrivalTime);
if (compare == 0)
compare = proc[k].priority.CompareTo(proc[i].priority);
if (compare == 0)
compare = proc[k].brust.CompareTo(proc[i].brust);
if (compare > 0)
{
// ...
}
which is the standard way of doing multi key comparison.
Upvotes: 0
Reputation: 95325
Rather than bubble sorting (which is the one of the least efficient ways to sort collections), why not just sort the collection using LINQ's OrderBy()
, e.g.
var sorted = proc.OrderBy(x => x.arrivalTime)
.ThenBy(x => x.priority)
.ThenBy(x => x.brust)
.ToList(); // or .ToArray() or whatever collection you need
Upvotes: 2
Reputation: 1538
Mahmoud, your if-statment is incorrect because it will evaluate to true if ALL conditions are met, your statement should cascade the conditions.
for (int k = 0; k < proc.Count; k++){
for (int i = k + 1; i < proc.Count; i++){
bool doSwap = false;
if (proc[k].arrivalTime > proc[i].arrivalTime)
{
doSwap = true;
}
else if (proc[k].arrivalTime == proc[i].arrivalTime)
{
if(proc[k].priority > proc[i].priority)
{
doSwap = true;
}
else if (proc[k].priority == proc[i].priority )
{
if(proc[k].brust > proc[i].brust)
{
doSwap = true;
}
}
}
if(doSwap)
{
temp = proc[i];
proc[i] = proc[k];
proc[k] = temp;
}
}
}
Upvotes: 0