简体   繁体   中英

Comparing adjacent elements in array to find greater element

I used the below code to compare the elements it gave me the output but the problem is only after the second loop gets over the first loop moves on to the next element. I don't want that to happen my intention is to just compare two neighbouring elements alone not an element with all array elements.

I tried using a single for loop then I encountered an exception while comparing the last two elements like if(i+1>i) the i+1th element will not present in the array.

my current output: 20th element is higher than10 30th element is higher than10 30th element is higher than20

my intended output: 20th element is higher than10 30th element is higher than20

import java.util.*;

public class HelloWorld {
  public static void main(String[] args) {
    int[] testarray={10,20,30};


    for(int i=0;i<testarray.length;i++)
    {

        for(int j=0;j<testarray.length;j++)
        {
            if (testarray[j]>testarray[i])
            {
                System.out.println(testarray[j]+"th element is higher than"+testarray[i]);


            }
        }


    }
  }
}

Change

for(int j=0;j<testarray.length;j++)

to start at i plus one and stop at i plus two. Like,

for(int j=i+1;j<testarray.length && j<i+2;j++)

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