Search code examples
cdynamic-arrays

Swapping the first value of a dynamic array with the maximum without changing the order of the rest


I've made a little program where i input a dimension of an array and then i fill it with values, then i tried to add a function where the first value of the array gets swapped with the biggest one, the problem i have is that all the other values (if we are considering that they are bigger than the first one) get swapped aswell in the process of the cycle, how do i avoid that?

void maxVectorSwap(int *v, int dim){
int i;
int app;
int max=0;
for(i=0;i<dim;i++){    
    max=v[0];
    if(v[i]>max){
        app=v[0];
        v[0]=v[i];
        v[i]=app;

    }   
}

printf("----------\n");
for(i=0;i<dim;i++){
    printf("v[%d]=%d\n",i,v[i]);                                       
}
printf("----------\n");  
}

Let's say i input the dimension of the array to be 5 and the values to be:

3 5 1 7 2

The result i get with this function is:

7 3 1 5 2

Which gives away that there more swaps, what i want instead is just to see 7 and 3 swapped so it would look like this:

7 5 1 3 2


Solution

  • To Solve this problem, lets look back at what our approach should be.

    Problem: Swapping the maximum and the first indexed number.

    Algorithm: To find where the maximum number is located and then swap the values using their indices. Thus try to find the index first and then try swapping.

    Updated Code:

    void maxVectorSwap(int *v, int dim)
    {
        int i;
        int app;
    
        //Lets assume the first element is the largerst number i.e index=0
        int indexOfMax=0;
    
        for(i=0;i<dim;i++)
        {    
            if(v[i]>v[indexOfMax])
            {
                indexOfMax=i;
                // store the updated maximum index in m
            }   
        }
    
        // now indexOfMax stores the location of the maximum number
        //Thus swapping now
        int temp=v[0];
        v[0]=v[indexOfMax];
        v[indexOfMax]=temp;
    
        printf("----------\n");
        for(i=0;i<dim;i++){
            printf("v[%d]=%d\n",i,v[i]);                                       
        }
        printf("----------\n");  
    }