给定n(n <= 5000)个互不相同的数,求如果使用插入排序使得数组升序的话,需要挪动多少个元素。
比如排好序的部分是1 3 4,这个时候要插入的元素是2,那么需要将3和4顺次往后挪一位,然后将2放到空出的位置中。所以挪动的元素个数是2.
Input
多组数据。每组数据的第一行是n,第二行是n个互不相同的数。
Output
对于每组数据输出一行表示答案。
Sample Input
4
1 3 2 4
4
1 3 4 2
Sample Output
1
2
#include <stdio.h>
#include <stdlib.h>
#define maxn 5002
int arr[maxn];
int times;
void insert_sort(int key,int i)
{
int j = i - 1;
int index = 0;
while(arr[j] > key && j >= 0)
{
arr[j+1] = arr[j];
j--;
times ++;
}
arr[j+1] = key;
return;
}
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF)
{
times = 0;
for(i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
insert_sort(arr[i],i);
}
printf("%d\n",times);
}
return 0;
}