//1、有一个整数数组,请求出两两之差绝对值最小的值
//方法1:两层for循环,求出每两个数之间的差的绝对值,再进行比较.算法时间复杂度:O(n^2)
//注意:若绝对值等于0,那么可以直接退出,因为绝对值等于0就是最小的了
#include <stdio.h>
#include <stdlib.h>
#define N 10
int minAbs(int *num);
void main()
{
int num[N] = {1,6,29,11,22,17,50,67,88,59};
int min;
min = minAbs(num);
printf("%d",min);
}
int minAbs(int *num)
{
int i,j;
int min,n;
min = abs(num[0] - num[1]);
for(i = 0;i < N;i++)
{
for(j = i+1;j <N;j++)
{
n =abs(num[i] - num[j]);
if(n ==0)
return0;
if(n< min)
{
min= n;
}
}
}
return min;
}
//方法2:对整个数组进行排序,需要O(n*logn)的时间。然后遍历一次数组,求相邻两个数之间的
//差的绝对值,若等于0,直接返回.需要O(n)的时间复杂度,总的时间复杂度需要O(n+n*logn)
//排序:用快排
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 10
int pattion(int num[],int p,int r);
void QuickSort(int num[],int p,int r);
int smallAbs(int *num);
void main()
{
int i;
int small;
int num[N] ={12,89,16,78,30,135,78,362,275,351};
QuickSort(num,0,N-1);
printf("经过快速排序之后数组如下:n");
for(i = 0;i < N;i++)
{
printf("]",num[i]);
}
printf("n");
small = smallAbs(num);
printf("数组中绝对值之差最小是]",small);
}
int pattion(int num[],int p,int r)
{
int i = p;
int j = r+1;
int x = num[p];
int temp;
while(1)
{
while(num[++i] <x);
while(num[--j] >x);
if(i >= j)
break;
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
num[p] = num[j];
num[j] = x;
return j;
}
void QuickSort(int num[],int p,int r)
{
if(p < r)
{
int q = pattion(num,p,r);
QuickSort(num,p,q-1);
QuickSort(num,q+1,r);
}
}
int smallAbs(int *num)
{
int i,k;
int small = abs(num[0] - num[1]);
if(0 == small)
return 0;
for(i = 1;i < N;i++)
{
k = abs(num[i],num[i+1]);
if(k <small)
{
small =k;
if(0 ==small)
return0;
}
}
return small;
}