The absolute value of the two element difference in the array is minimized

Source: Internet
Author: User

#include <stdio.h> #include <stdlib.h>/* given an integer array of n elements, find the two elements in the array x and y make the ABS (x-y) value The least *//* thought: sort, It then iterates through the array to compare the values of the adjacent values by subtracting the value */typedef struct{int num1;int num2;} Twonumber; Twonumber Gettnumber (int* numbers, int length), int cmp (const void *a,const void *b), int abs (int number), int main () {int n;w Hile (printf ("Please input n:\n"), Fflush (stdin), scanf ("%d", &n)! = EOF) {if (n < 2) {printf ("Please input a bigger Number.\n "); continue;} int *numbers = (int*) malloc (n*sizeof (int));p rintf ("Please input%d numbers: \ n", n); for (int i = 0; i < n; ++i) scanf ("%d ", numbers + i); Twonumber Tnumber = Gettnumber (numbers,n);p rintf ("%d%d\n", tnumber.num1,tnumber.num2);} System ("pause"); return 0;} Twonumber Gettnumber (int* numbers, int length) {qsort (numbers,length,sizeof (int), CMP); int absminus = ABS (Numbers[0]- NUMBERS[1]); int index = 0;for (int i = 1; i < length-1; ++i) {if (Absminus > abs (numbers[i]-numbers[i + 1]) {ABSM Inus = ABS (Numbers[i]-numbers[i + 1]); index = i;}} Twonumber Tnumber;tnumbeR.NUM1 = numbers[index];tnumber.num2 = Numbers[index + 1];return Tnumber;} int cmp (const void *a, const void *b) {return * (int*) A-* (int*) b;} int abs (int number) {if (number > 0) return number;elsereturn-number;}

  

The absolute value of the two element difference in the array is minimized

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.