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

Java 24 Programs TCS

The document provides algorithms for various array operations including finding the smallest and largest elements, second smallest and largest, sum, average, median, reversing the array, and searching for an element. Each operation includes example inputs and outputs along with TCS tricks to optimize the process. The tricks emphasize efficient comparisons, sorting for order-based retrieval, and avoiding unnecessary space usage.

Uploaded by

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

Java 24 Programs TCS

The document provides algorithms for various array operations including finding the smallest and largest elements, second smallest and largest, sum, average, median, reversing the array, and searching for an element. Each operation includes example inputs and outputs along with TCS tricks to optimize the process. The tricks emphasize efficient comparisons, sorting for order-based retrieval, and avoiding unnecessary space usage.

Uploaded by

Pavithra R.K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Smallest Element

int min = arr[0];


for(int i=1;i<n;i++){
if(arr[i] < min)
min = arr[i];
}

Example: Input: 5 → 3 1 4 2 5 | Output: 1


TCS Trick: Always assume first element as min to reduce comparisons.

2. Largest Element

int max = arr[0];


for(int i=1;i<n;i++){
if(arr[i] > max)
max = arr[i];
}

Example: Input: 5 → 3 1 4 2 5 | Output: 5


TCS Trick: Same logic as min, just reverse comparison.

3. Second Smallest & Largest

[Link](arr);
[Link](arr[1]);
[Link](arr[n-2]);

Example: Input: 5 → 1 2 3 4 5 | Output: 2 4


TCS Trick: Sorting makes finding order-based elements easy.

4. Sum

int sum = 0;
for(int i=0;i<n;i++)
sum += arr[i];

Example: Input: 3 → 1 2 3 | Output: 6


TCS Trick: Use loop accumulation.

5. Average

double avg = (double)sum/n;

Example: Input: 3 → 1 2 3 | Output: 2.0


TCS Trick: Type casting avoids integer division.

6. Median

[Link](arr);
if(n%2==0)
[Link]((arr[n/2]+arr[n/2-1])/2.0);
else
[Link](arr[n/2]);

Example: Input: 5 → 1 2 3 4 5 | Output: 3


TCS Trick: Always sort before median.

7. Reverse

for(int i=n-1;i>=0;i--)
[Link](arr[i]);

Example: Input: 3 → 1 2 3 | Output: 3 2 1


TCS Trick: No extra space needed.

8. Search Element
if(arr[i]==key)
[Link]("Found");

Example: Input: key=2 → 1 2 3 | Output: Found


TCS Trick: Linear search simplest.

You might also like