Reputation: 79
int RiskSort(int* PlayerA, int* PlayerB,int Length){
int i,j;
int Losses = 0;
for(i=0;i<Length-Losses;i++){
printf("%d,%d\n",PlayerA[i],PlayerB[i]);
if(PlayerB[i]<PlayerA[i]){
for(j=i;j<((Length-1)-Losses);j++){
Swap(&PlayerB[j],&PlayerB[j+1]);
}
i--;
Losses++;
}
}
return Losses;
}
I just wrote this and I am getting O(n log n) as my answer, This is homework but the Big O part is just my way of studying.
Thanks again
Edit: I am getting N from the first for loop and N-1-X amount of passes on the if, and i am unsure how to notate that so since it limits the amount of passes i called it log n ( probably inaccurate but I couldn't find a guide that wasn't look at code and pick online)
Edit 2: Just trying to make this function more efficient
int RiskSortB(int* PlayerA, int* PlayerB,int Length){
int i,j;
int Losses = 0;
for(i=0;i<Length-Losses;i++){
j=i+1;
if(PlayerB[i]<PlayerA[i])
Losses++;
while(PlayerB[i]<PlayerA[i]&&j<Length){
if(PlayerB[j]>=PlayerA[i]){
Swap(&PlayerB[i],&PlayerB[j]);
if(j!=(Length-Losses))
Swap(&PlayerB[j],&PlayerB[Length-Losses]);
}
j++;
}
}
return Losses;
}
So since the amount of time maximum Swap is called per for loop is 2 it means its O(2N) but constants don't matter so its O(N) right?
Upvotes: 4
Views: 53
Reputation: 385950
Suppose every element of PlayerB
causes a “loss”. For the first element, you perform Length-1 swaps. For the second element, you perform Length-2 swaps. For the third element, you perform Length-3 swaps. Etc.
How many swaps total? As many as 1 + 2 + ... + (n-1). When you see this procession of integers, apply Gauss's formula: the sum of the integers 1..n = n * (n + 1) / 2 = (n2 + n) / 2. That is O(n2).
(The difference between sum(1..n) and sum(1..(n-1)) doesn't affect the big-O.)
Upvotes: 4