简体   繁体   中英

Array shifting and rearranging

So I am trying to search an array for a value and if found I want to remove that value from the array and place it at the front of the array shifting the rest before its position down 1. "Tag" is the value being searched. My results don't exactly seem to be right. Not the best at this hoping someone can explain what I did wrong and how I should fix it. This is in C.

         if (replacement == 1) { 
//Search arrays for value (tag)
      int j,k;
      //MRU hit
       for(j=0; j<=lines; j++){
         if(MRU[j] == tag){
          printf("Hit!"" \n");
          hits++;
           h = 1;
           k=j;
            temp1 = MRU[j - 1];  
            for(k = j; k > 0; k--) { 
            MRU[k] = MRU[k - 1];  
            MRU[0] = tag;
            }
           break;
         
           }
         }
    #include<stdio.h>  
  
#define N 5  
  
int main()  
{  
    int a[N], i, temp, pos, dir;  
  
    printf("Enter %d integer numbers\n", N);  
    for(i = 0; i < N; i++)  
        scanf("%d", &a[i]);  
  
    printf("Enter the number of positions to shift\n");  
    scanf("%d", &pos);  
  
    printf("Enter the direction of shifting ...\n");  
    printf("LEFT: 1 and RIGHT: 0\n");  
    scanf("%d", &dir);  
  
    while(pos)  
    {  
        if(dir)  
        {  
            temp = a[0];  
            for(i = 0; i < N - 1; i++)  
                a[i] = a[i + 1];  
  
            a[N - 1] = temp;  
        }  
        else  
        {  
            temp = a[N - 1];  
            for(i = N - 1; i > 0; i--)  
                a[i] = a[i - 1];  
  
            a[0] = temp;  
        }  
  
        pos--;  
    }  
  
    printf("Array after shift operation ...\n");  
    for(i = 0; i < N; i++)  
        printf("%d\n", a[i]);  
  
    printf("\n");  
  
    return 0;  
} 

I don't quite understand your issue because I am still a beginner in C programming but, This might be helpful to you https://technotip.com/8964/c-program-to-shift-elements-of-an-array-by-n-position/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM