Sorting
Time limit1sMemory limit128 MB
Count the swaps made by a given selection-style double loop on an array.
Statement
Genetic Programming is a method for automatically constructing computer programs. A Genetic Programming algorithm tries to find a program that, for some input, produces a desired result. It is an evolutionary method: the search for a suitable program is carried out through artificial evolution, a mechanism modeled on biological evolution.
Using Genetic Programming, the integer-sorting algorithm sort() shown below (in C) was evolved. This algorithm is correct and sorts the numbers from largest to smallest. Its innermost loop calls the helper procedure swap(). Can you quickly count how many times swap() runs for a given array ?
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void sort(int t[], int N)
{
int i, j;
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
if (t[i] > t[j])
swap(&t[i], &t[j]);
}
Input
The first line contains a natural number (), the number of tests.
For each test, the first line contains (), the size of the array . The second line contains the elements of , where for .
Output
For each test, print on a single line the number of times the swap() procedure is called.