How do I swap two integers in an array, where my method takes in two integers and an array from main?

后端 未结 4 717
既然无缘
既然无缘 2020-12-12 06:17

I call my swap method in main, but it doesn\'t change anything. What am I doing wrong?

public static void main(String[] args){


    int mainArr[] = new int[         


        
相关标签:
4条回答
  • 2020-12-12 06:45

    Move the method call: -

    swapper(3, 14, mainArr);
    

    outside your for loop. Since, if your loop runs even number of times, it will not affect the array.

    Also, you need to initialize your array first, before actually swapping the elements. That you would need to do before invoking swapper.

    for(int i = 0; i<mainArr.length; i++){
        mainArr[i] = i;
    }
    
    swapper(3, 14, mainArr);
    
    for(int i = 0; i<mainArr.length; i++){
        System.out.print(i + mainArr[i] + " ");
    }
    
    0 讨论(0)
  • 2020-12-12 06:54
    public class swapInt
    { 
    public static void main(String args[])
    {
    
    
    swap(new int[]{2,3,5,6,8},1,3);
    
    
    }
    public static void swap(int[]a,int i,int j)
    {
        int temp=a[i];
        a[i]= a[j];
        a[j]=temp;
        for(int b=0;b<a.length;b++)
        {
    
        System.out.println(a[b]);
        }
     }
    }
    
    0 讨论(0)
  • 2020-12-12 06:58

    You are calling swapper the same number of times as there are elements in your array.

    • If the array has a even length, nothing will change
    • If the array has a odd length, it will change
    0 讨论(0)
  • 2020-12-12 07:04

    Writing the code as so:

    int mainArr[] = new int[20];  
    
    for(int i =0; i <mainArr.length;i++)  
    {  
        mainArr[i]=i;
    }  
    
    swapper(3,14,mainArr); 
    

    will resolve the issue. The problem was you happened to be calling swap an even number of times, so it had a total effect of nothing.

    0 讨论(0)
提交回复
热议问题