Search code examples
arrayscfor-loopif-statementreverse

reverse array in range in C


I have to solve it in C language. I have arrays with n integers. L and U are lower and upper bound. I have to reverse numbers in array which is in [L,U]. I tried it by this way, but in some cases the answer is wrong. What mist be changed in the code? Or is there any other logic to complete the task?

#include <stdio.h>
int main() {
  int x, arr[100], n, l, u, a, temp, temp1;
  scanf("%d%d%d", &n, &l, &u);
  for (int i = 0; i < n; i++) {
    scanf("%d", &x); // read elements of an array
    arr[i] = x;
  }
  a = n / 2;
  for (int i = 0; i < a; i++) {
    for (int j = a; j < n; j++) {
      if (arr[i] >= l && arr[i] <= u) {
        if (arr[j] >=l && arr[j] < u) {
          temp = arr[j];
          temp1 = arr[i];
          arr[i] = temp;
          arr[j] = temp1;
        }
      }
    }
  }

  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
}

sample input: 10(number of integers) -7(lower bound) 5(upper bound) -10 -9 5 -2 -3 7 10 6 -8 -5

sample output: -10 -9 -5 -3 -2 7 10 6 -8 5

my output: -10 -9 -5 -2 -3 7 10 6 -8 5


Solution

  • You made a valiant attempt. Your nested for() loops are appropriate for some kinds of sorting algorithms, but not for what seems to be the purpose of this task.

    From the sample input and desired output, you really want to establish a 'bracket' at either end of the array, then shift both toward the centre, swapping elements whose value happens to satisfy
    low <= n <= high value. (In this case, -7 <= n <= 5).

    Here's a solution:

    #include <stdio.h>
    
    int swap( int arr[], size_t l, size_t r ) { // conventional swap algorithm
        int t = arr[l];
        arr[l] = arr[r];
        arr[r] = t;
        return 1;
    }
    
    int main() {
        int arr[] = { -10, -9, 5, -2, -3, 7, 10, 6, -8, -5, }; // your data
        size_t i, sz = sizeof arr/sizeof arr[0];
    
        for( i = 0; i < sz; i++ ) // showing original version 
            printf( "%d ", arr[i] );
        putchar( '\n' );
    
    #define inRange( x ) ( -7 <= arr[x] && arr[x] <= 5 ) // a good time for a macro
    
        size_t L = 0, R = sz - 1; // 'L'eft and 'R'ight "brackets"
        do {
            while( L < R && !inRange( L ) ) L++; // scan from left to find a target
            while( L < R && !inRange( R ) ) R--; // scan from right to find a target
        } while( L < R && swap( arr, L, R ) && (L+=1) > 0 && (R-=1) > 0 );
    
        for( i = 0; i < sz; i++ ) // showing results
            printf( "%d ", arr[i] );
        putchar( '\n' );
    
        return 0;
    }
    
    -10 -9 5 -2 -3 7 10 6 -8 -5
    -10 -9 -5 -3 -2 7 10 6 -8 5