title: C program that sorts in ascending order difference of two consecutive array elements
body: <p>I need to make a program that will sort the difference of consecutive array elements in ascending order. For exemple: the difference between first and second element is the smallest, the difference between second and 3rd is bigger and so on. I can't come up with a good algorithm to sort the array in desired way. The only thing I've come up with is switching places of 2 elements, then if order isn't right switch again and keep that until its sorted. I'm pretty sure its not well executed either.</p>
  
  <p>Here is my code: </p>
  
  <pre><code>#include&lt;stdio.h&gt;
  void InputArray(int a[], int size);
  void PrintArray(int a[], int size);
  void sort(int a[], int size);
  
  void main(){
      int a[100], i, n;
  do{
      printf("Number of elements: ");
      scanf("%d", &amp;n);
  } while (n &lt; 1 || n &gt; 100);
  
  InputArray(a, n);
  sort(a, n);
  PrintArray(a, n);
  printf("\n");
  }
  
  void InputArray(int a[], int size){
      printf("Enter array elements:\n");
  for (int i = 0; i &lt; size; i++)
      scanf("%d", &amp;a[i]);
  }
  void sort(int a[], int size){
      int i, temp;
  for (i = 0; ;i++){
      if ((a[i] - a[i + 1]) &lt; (a[i + 1] - a[i + 2]))
          break;
      temp = a[i];
      a[i] = a[i + 1];
      a[i + 1] = temp;
  
      if (i == size - 1){
          temp = a[size - 1];
          a[size - 1] = a[0];
          a[0] = temp;
          i = -1;
      }
   }
   }
    void PrintArray(int a[], int size){
      printf("Sorted array:\n");
      for (int i = 0; i &lt; size; i++)
      printf("%d ", a[i]);
  }
  </code></pre>
  
  <p>Example output:</p>
  
  <pre><code> Number of elements: 4
   Enter array elements:
   1 3 7 12
   Sorted array:
   1 7 12 3
  </code></pre>
  
  <p>But I'm getting 3 1 7 12 during testing. </p>