0% found this document useful (0 votes)
6 views2 pages

Array (Lecture)

The document contains Java code snippets for finding the largest and second largest numbers in an array, as well as for rotating an array. The first part demonstrates both brute force and optimal methods for finding the largest number, while the second part focuses on identifying the second largest number. The final section provides a method for rotating an array using a three-step reversal technique.

Uploaded by

mdhulasi2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Array (Lecture)

The document contains Java code snippets for finding the largest and second largest numbers in an array, as well as for rotating an array. The first part demonstrates both brute force and optimal methods for finding the largest number, while the second part focuses on identifying the second largest number. The final section provides a method for rotating an array using a three-step reversal technique.

Uploaded by

mdhulasi2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

Largest NUmber:
///Brute force:

package main;

import java.util.Scanner;

public class hello


{
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
int n=sc.nextInt();
int []arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Sorted Array is :"+array(arr));

}
public static int array(int []arr)
{

int max=arr[0];
for(int i=0;i<arr.length;i++)
{
if(max<arr[i])
{
max=arr[i];
}
}
return max;
}

}
///Optimal
Arrays.sort(arr);
return (arr[arr.length-1]);
///
2.second large
//
public static int array(int []arr)
{

int large=arr[0];
int slarge=-1;
for(int i=0;i<arr.length;i++){
if(arr[i]>large)
{
slarge=large;
large=arr[i];
}
else if(arr[i]<large&&arr[i]>slarge)
{
slarge=arr[i];
}
}
return slarge;
}

3.////rotate an array:
public static void aee (int []arr,int s,int e)
{
while(s<=e)
{
int t=arr[s];
arr[s]=arr[e];
arr[e]=t;
s++;e--;

}
}

public static int[] rotateArray(int[] arr, int n,int d)


{
/*int []temp=new int[d];
for(int i=0;i<d;i++)
{
temp[i]=arr[i];
}
for(int i=d;i<n;i++)
{
arr[i-d]=arr[i];

}
for(int i=n-d;i<n;i++)
{
arr[i]=temp[i-(n-d)];
}
return arr;*/
aee(arr,0,d-1);
aee(arr,d,n-1);
aee(arr,0,n-1);
return arr;

You might also like