Find the two elements x and y in the array so that the value of abs(x-y) is the smallest

 Ideas:

Sort the array first, the result after sorting: a0 a1 a2 .... an

Find the minimum value in {|a0-a1| |a1-a2| |a2-a3| .... |an-1-an|}

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>

int main()
{
	int A[20] = { 1,12,20,7,3,17,4 }; 
	int size = 7;
	for (int i = 0; i < size - 1; i++)//冒泡排序
	{
		for (int j = size - 1; j > i; j--)
		{
			if (A[j] < A[j - 1])
			{
				int t = A[j];
				A[j] = A[j - 1];
				A[j - 1] = t;
			}
		}
	}
	int min = abs(A[0] - A[1]);
	int x = A[0] , y = A[1];
	for (int i = 1; i < size-1; i++)
	{
		if (abs(A[i] - A[i + 1]) < min)
		{
			x = A[i];
			y = A[i + 1];
			min = abs(A[i] - A[i + 1]);
		}
	}
	printf("两个元素是%d %d,最小值=%d\n" , x , y , min);
	return 0;
}

 

 

 

Guess you like

Origin blog.csdn.net/qq_43496435/article/details/113805244