#include<stdio.h>
void quickSort(int *A,int start,int end,int *step);
void quickSort(int *A,int start,int end,int *step)
{
int i = start;
int j = end;
int temp = A[start];
if(i<j)
{
while(i<j)
{
while(i<j && temp<A[j])
{
j--;
}
if(i<j)
{
A[i++] = A[j];
(*step)++;
}
while(i<j && temp>A[i])
i++;
if(i<j)
{
A[j--] = A[i];
(*step)++;
}
}
if(i<j)
A[i] = temp;
quickSort(A,start,i-1,step);
quickSort(A,i+1,end,step);
}
}
int main(void)
{
int i;
int cnt;
int step=0;
int A[200000];
scanf("%d",&cnt);
while(cnt!=0)
{
for(i=0; i<cnt; i++)
scanf("%d",&A[i]);
quickSort(A,0,cnt-1,&step);
printf("%d",step);
step=0;
scanf("%d",&cnt);
}
}
void quickSort(int *A,int start,int end,int *step);
void quickSort(int *A,int start,int end,int *step)
{
int i = start;
int j = end;
int temp = A[start];
if(i<j)
{
while(i<j)
{
while(i<j && temp<A[j])
{
j--;
}
if(i<j)
{
A[i++] = A[j];
(*step)++;
}
while(i<j && temp>A[i])
i++;
if(i<j)
{
A[j--] = A[i];
(*step)++;
}
}
if(i<j)
A[i] = temp;
quickSort(A,start,i-1,step);
quickSort(A,i+1,end,step);
}
}
int main(void)
{
int i;
int cnt;
int step=0;
int A[200000];
scanf("%d",&cnt);
while(cnt!=0)
{
for(i=0; i<cnt; i++)
scanf("%d",&A[i]);
quickSort(A,0,cnt-1,&step);
printf("%d",step);
step=0;
scanf("%d",&cnt);
}
}