//************************************** ********
//
// Telephone bill delivery algorithm
// Xwlee 2006/12/20
//************************************** ********
# Include <iostream>
# Include <ctime>
# Include <iomanip>
Using namespace STD;
Const int n= 100;
Struct phone {
Int phone_num;
Int flag;
};
Void Merge (struct phone a [], int P, int Q, int R );
Void merge_sort (struct phone a [], int P, int R );
Int main ()
{
Struct phone my_phone [N];
Int I;
Srand (unsigned) Time (null); // The srand () function generates a Random Seed starting from the current time
For (I = 0; I <n; I ++)
{
While (my_phone [I]. phone_num = rand () % 1000000) <10000)
;
My_phone [I]. Flag = rand () % 2;
}
Cout <"original n phone bills:" <Endl;
For (I = 0; I <n; I ++)
Cout <"no. "<SETW (5) <I <" phone number: "<SETW (10) <my_phone [I]. phone_num <"whether to pay (1/0):" <my_phone [I]. flag <Endl;
Merge_sort (my_phone, 0, N );
Cout <Endl <"n phone bills after pre-sorting:" <Endl;
For (I = 0; I <n; I ++)
Cout <"no. "<SETW (5) <I <" phone number: "<SETW (10) <my_phone [I]. phone_num <"whether to pay (1/0):" <my_phone [I]. flag <Endl;
Return 0;
}
Void Merge (struct phone a [], int P, int Q, int R)
{
Int n1 = Q-p + 1;
Int n2 = r-Q;
Struct phone * l = new struct phone [N1];
Struct phone * r = new struct phone [n2];
Int I = 0;
Int J = 0;
For (INT m = 0; m <N1; m ++)
{
L [M]. phone_num = A [p + M]. phone_num;
L [M]. Flag = A [p + M]. flag;
}
For (INT n = 0; n <N2; n ++)
{
R [N]. phone_num = A [q + n + 1]. phone_num;
R [N]. Flag = A [q + n + 1]. flag;
}
Int K = P;
For (K; k <= r; k ++)
{
If (L [I]. phone_num <= R [J]. phone_num)
{
A [K]. phone_num = L [I]. phone_num;
A [K]. Flag = L [I]. flag;
I ++;
}
Else
{
A [K]. phone_num = R [J]. phone_num;
A [K]. Flag = R [J]. flag;
J ++;
}
If (I> = N1) | (j> = n2 ))
Break;
}
While (I> = N1 & J <N2) // when one side is over,
{
K ++;
A [K]. phone_num = R [J]. phone_num;
A [K]. Flag = R [J]. flag;
J ++;
}
While (I <N1 & J> = n2)
{
K ++;
A [K]. phone_num = L [I]. phone_num;
A [K]. Flag = L [I]. flag;
I ++;
}
}
Void merge_sort (struct phone a [], int P, int R)
{
Int Q;
If (P <R)
{
Q = (p + r)/2;
Merge_sort (A, p, q );
Merge_sort (A, q + 1, R );
Merge (A, P, Q, R );
}
}