Search code examples
arrayscmaxswap

how to swap two max elements in the same array?


I was thinking of how can i swap this two elements from an given array,for example if i find two maximums in one array and i want to swap them how can i do that without using another array ?

#include <stdio.h>

int main()
{
int n,i;
int arr[100];



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

//1 2 3 4 5

for example this array should be 1 2 3 5 4

int max1 = arr[0],max2 = arr[0];
for(i = 0;i < n;i++){
    if(max1 < arr[i]){
        max2 = max1;
        max1 = arr[i];

    }
    else if(max2 < arr[i]){
        max2 = arr[i];
    }

}
printf("%d %d",max1,max2);
return 0;
}

Solution

  • Instead of defining max1 and max2 as array values define them as indices. For example

    int max1 = 0, max2 = 0;
    for ( i = 1;i < n; i++ ){
        if( arr[max1] < arr[i] ){
            max2 = max1;
            max1 = i;
    
        }
        else if( arr[max2] < arr[i]){
            max2 = i;
        }
    }
    
    if ( max1 != max2 && arr[max1] != arr[max2] )
    {
        int tmp = arr[max1];
        arr[max1] = arr[max2];
        arr[max2] = tmp;
    }
    
    printf("%d %d",arr[max1],arr[max2]);
    

    Or you may swap the elements unconditionally.

    int tmp = arr[max1];
    arr[max1] = arr[max2];
    arr[max2] = tmp;