0% found this document useful (0 votes)
19 views

Program To Copy All Elements of One Array Into Another Array

Uploaded by

nishajayakumarg
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Program To Copy All Elements of One Array Into Another Array

Uploaded by

nishajayakumarg
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Java Array Programs

Program to copy all elements of one array into another


array

In this program, we need to copy all the elements of one array into
another. This can be accomplished by looping through the first array and
store the elements of the first array into the second array at the
corresponding position.

ARRAY 1
1 2 3 4 5

ARRAY 2
1 2 3 4 5

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr1[] ={1, 2, 3, 4, 5}
o STEP 3: CREATE arr2[] of size arr1[].
o STEP 4: COPY elements of arr1[] to arr2[]
o STEP 5: REPEAT STEP 6 UNTIL (i<arr1.length)
o STEP 6: arr2[i] =arr1[i]
o STEP 7: DISPLAY elements of arr1[].
o STEP 8: REPEAT STEP 9 UNTIL (i<arr1.length)
o STEP 9: PRINT arr1[i]
o STEP 10: DISPLAY elements of arr2[].
o STEP 11: REPEAT STEP 12 UNTIL (i<arr2.length)
o STEP 12: PRINT arr2[i].
o STEP 13: END
Program:

public class CopyArray {


public static void main(String[] args) {
//Initialize array
int [] arr1 = new int [] {1, 2, 3, 4, 5};
//Create another array arr2 with size of arr1
int arr2[] = new int[arr1.length];
//Copying all elements of one array into another
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
//Displaying elements of array arr1
System.out.println("Elements of original array: ");
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}

System.out.println();

//Displaying elements of array arr2


System.out.println("Elements of new array: ");
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
}
}

Output:

Elements of original array


1 2 3 4 5
Elements of new array:
1 2 3 4 5
Next TopicJava Programs

Program to find the frequency of each element in the array

In this program, we have an array of elements to count the occurrence of its


each element. One of the approaches to resolve this problem is to maintain one
array to store the counts of each element of the array. Loop through the array
and count the occurrence of each element as frequency and store it in another
array fr.

1. 1 2 8 3 2 2 2 5 1

In the given array, 1 has appeared two times so its frequency be 2 and 2 has
appeared four times so have frequency 4 and so on.

Algorithm

 STEP 1: START
 STEP 2: INITIALIZE arr[] ={1, 2, 8, 3, 2, 2, 2, 5, 1 }.
 STEP 3: CREATE fr[] of arr[] length.
 STEP 4: SET visited = -1.
 STEP 5: REPEAT STEP 6 to STEP 9 for(i=0;i<arr.length;i++)
 STEP 6: SET count = 1
 STEP 7: REPEAT STEP 8 for(j=i+1;j<arr.length;j++)
 STEP 8: if(arr[i]==arr[j]) then
count++
fr[j] =visited
 STEP 9: if(fr[i]!=visited) then
fr[i]=count
 STEP 10: PRINT "------------"
 STEP 11: PRINT "Element | Frequency"
 STEP 12: PRINT "-------------"
 STEP 13: REPEAT STEP 14 for(i=0;i<fr.length;i++)
 STEP 14: if(fr[i]!=visited) then
PRINT arr[i] and fr[i]
 STEP 15: PRINT "-------------"
 STEP 16: END

Program:

public class Frequency {


public static void main(String[] args) {

//Initialize array

int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};

//Array fr will store frequencies of element

int [] fr = new int [arr.length];

int visited = -1;

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

int count = 1;

for(int j = i+1; j < arr.length; j++){

if(arr[i] == arr[j]){

count++;

//To avoid counting same element again

fr[j] = visited;

if(fr[i] != visited)

fr[i] = count;

//Displays the frequency of each element present in array

System.out.println("---------------------------------------");

System.out.println(" Element | Frequency");

System.out.println("---------------------------------------");
for(int i = 0; i < fr.length; i++){

if(fr[i] != visited)

System.out.println(" " + arr[i] + " | " + fr[i]);

System.out.println("----------------------------------------");

}}

Output:

----------------------------------------
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1
----------------------------------------
Next TopicJava Programs

Program to left rotate the elements of an array

In this program, we need to rotate the elements of an array towards the


left by the specified number of times. In the left rotation, each element
of the array will be shifted to its left by one position and the first element
of the array will be added to end of the list. This process will be followed
for a specified number of times.

Consider above array, if n is 1 then, all elements of the array will be


moved to its left by one position such that second element of the array
will take the first position, the third element will be moved to the second
position and so on. The first element of the array will be added to the
last of the array.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] ={1, 2, 3, 4, 5 }.
o STEP 3: SET n =3
o STEP 4: PRINT "Original Array"
o STEP 5: REPEAT STEP 6 for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 12 for(i=0; i<n; i++ )
o STEP 8: DEFINE j, first.
o STEP 9: first = arr[0]
o STEP 10: REPEAT STEP 11 for(j= 0; j<arr.length-1; j++)
o STEP 11: arr[j]= arr[j+1]
o STEP 12: arr[j]= first
o STEP 13: PRINT "Array after left rotation"
o STEP 14: REPEAT STEP 15 for(i=0; i<arr.length; i++)
o STEP 15: PRINT arr[i]
o STEP 16: END

Program:

class RotateLeft {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//n determine the number of times an array should be rotated
int n = 3;
//Displays original array
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Rotate the given array by n times toward left
for(int i = 0; i < n; i++){
int j, first;
//Stores the first element of the array
first = arr[0];
for(j = 0; j < arr.length-1; j++){
//Shift element of array by one
arr[j] = arr[j+1];
}
//First element of array will be added to the end
arr[j] = first;
}
System.out.println();
//Displays resulting array after rotation
System.out.println("Array after left rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}

Output:

Original Array:
1 2 3 4 5
Array after left rotation:
4 5 1 2 3
Next TopicJava Programs

Program to print the duplicate elements of an array


In this program, we need to print the duplicate elements present in the
array. This can be done through two loops. The first loop will select an
element and the second loop will iteration through the array by
comparing the selected element with other elements. If a match is found,
print the duplicate element.

In the above array, the first duplicate will be found at the index 4 which is
the duplicate of the element (2) present at index 1. So, duplicate
elements in the above array are 2, 3 and 8.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[]= {1, 2, 3, 4, 2, 7, 8, 8, 3}.
o STEP 3: PRINT "Duplicate elements in given array:"
o STEP 4: REPEAT STEP 5 to STEP 7 for(i=0; i<arr.length; i++)
o STEP 5: REPEAT STEP 6 and STEP 7 for(j=i+1; j<arr.length; j++)
o STEP 6: if(arr[i] == arr[j])
o STEP 7: PRINT arr[j]
o STEP 8: END

Program:

public class DuplicateElement {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
}

Output:

Duplicate elements in given array:


2
3
8
Next TopicJava Programs

Program to print the elements of an array

This is a simple program to create an array and then to print it's all
elements.

Now, just know about arrays.

Arrays are the special variables that store multiple values under the same
name in the contiguous memory allocation. Elements of the array can be
accessed through their indexes.

Here, 1, 2, 3, 4 and 5 represent the elements of the array. These elements


can be accessed through their corresponding indexes, 1.e., 0, 1, 2, 3 and
4.

Play Video

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}.
o STEP 3: PRINT "Elements of given array:"
o STEP 4: REPEAT STEP 5 for(i=0; i<arr.length; i++)
o STEP 5: PRINT arr[i]
o STEP 6: END

Program:

public class PrintArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array: ");
//Loop through the array by incrementing value of i
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

Output:

Elements of given array:


1 2 3 4 5

Program to print the elements of an array in reverse order

In this program, we need to print the elements of the array in reverse


order that is; the last element should be displayed first, followed by
second last element and so on.
Above array in reversed order:

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}
o STEP 3: PRINT "Original Array:"
o STEP 4: REPEAT STEP 5 for(i=0; i<arr.length ; i++)
o STEP 5: PRINT arr[i]
o STEP 6: PRINT "Array in reverse order"
o STEP 7: REPEAT STEP 8 for(i= arr.length-1; i>=0; i--)
o STEP 8: PRINT a[i]
o STEP 9: END

Program:

public class ReverseArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

Output:

Original array:
1 2 3 4 5
Array in reverse order:
5 4 3 2 1
Next TopicJava Programs

Program to print the elements of an array present on even


position

In this program, we need to print the element which is present on even


position. Even positioned element can be found by traversing the array
and incrementing the value of i by 2.

In the above array, elements on even position are b and d.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}
o STEP 3: PRINT "Elements of given array present on even position:"
o STEP 4: REPEAT STEP 5 for(i=1; i< arr.length; i= i+2)
o STEP 5: PRINT arr[i]
o STEP 6: END

Program:
public class EvenPosition {
public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};

System.out.println("Elements of given array present on even position: "


);
//Loop through the array by incrementing value of i by 2
//Here, i will start from 1 as first even positioned element is present at
position 1.
for (int i = 1; i < arr.length; i = i+2) {
System.out.println(arr[i]);
}
}
}

Output:

Elements of given array present on even position:


2
4
Next TopicJava Programs

Program to print the elements of an array present on odd


position

In this program, we need to print the elements of the array which are
present in odd positions. This can be accomplished by looping through
the array and printing the elements of an array by incrementing i by 2 till
the end of the array is reached.
In the above array, the elements present on odd positions are a, c and e.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}
o STEP 3: PRINT "Elements of given array present on odd position:"
o STEP 4: REPEAT STEP 5 for(i=0; i< arr.length; i= i+2)
o STEP 5: PRINT arr[i]
o STEP 6: END

Program:

public class OddPosition {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array present on odd position: ");

//Loop through the array by incrementing value of i by 2


for (int i = 0; i < arr.length; i = i+2) {
System.out.println(arr[i]);
}
}
}

Output:

Elements of given array present on odd position:


1
3
5
Next TopicJava Programs

Program to print the largest element in an array


In this program, we need to find out the largest element present in the
array and display it. This can be accomplished by looping through the
array from start to end by comparing max with all the elements of an
array. If any of element is greater than max, then store a value of the
element in max. Initially, max will hold the value of the first element. At
the end of the loop, max represents the largest element in the array.

In the above array, initially, max will hold the value 25. In the 1st
iteration, max will be compared with 11, since 11 is less than max. Max
will retain its value. In the next iteration, it will be compared to 7, 7 is also
less than max, no change will be made to the max. Now, max will be
compared to 75. 75 is greater than max so that max will hold the value of
75. Continue this process until the end of the array is reached. At the end
of the loop, max will hold the largest element in the array.

Algorithm

1. STEP 1: START
2. STEP 2: INITIALIZE arr[] = {25, 11, 7, 75, 56}
3. STEP 3: max = arr[0]
4. STEP 4: REPEAT STEP 5 for(i=0; i< arr.length; i++)
5. STEP 5: if(arr[i]>max) max=arr[i]
6. STEP 6: PRINT "Largest element in given array:"
7. STEP 7: PRINT max
8. STEP 8: END

Program:

public class LargestElement_array {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in given array: " + max);
}
}

Output:

Largest element present in given array: 75


Next TopicJava Programs

← PrevNext →

Program to print the smallest element in an array

In this program, we need to find out the smallest element present in the
array. This can be achieved by maintaining a variable min which initially
will hold the value of the first element. Loop through the array by
comparing the value of min with elements of the array. If any of the
element's value is less than min, store the value of the element in min.

Consider above array. Initially, min will hold the value 25. In the 1st
iteration, min will be compared with 11. Since 11 is less than 25. Min will
hold the value 11. In a 2nd iteration, 11 will be compared with 7. Now, 7
is less than 11. So, min will take the value 7. Continue this process until
the end of the array is reached. At last, min will hold the smallest value
element in the array.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] = {25, 11, 7, 75, 56}
o STEP 3: min = arr[0]
o STEP 4: REPEAT STEP 5 for(i=0; i< arr.length; i++)
o STEP 5: if(arr[i]<min)
min=arr[i]
o STEP 6: PRINT "Smallest element in given array:"
o STEP 7: PRINT min
o STEP 8: END

Program:

public class SmallestElement_array {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize min with first element of array.
int min = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with min
if(arr[i] <min)
min = arr[i];
}
System.out.println("Smallest element present in given array: " + min);
}
}

Output:

Smallest element present in given array: 7


Next TopicJava Programs

← PrevNext →

Java Program to print the number of elements present in


an array

In this program, we need to count and print the number of elements


present in the array.

The number of elements present in the array can be found by calculating


the length of the array.

Length of above array is 5. Hence, the number of elements present in the


array is 5.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr = {1,2,3,4,5}
o STEP 3: PRINT arr.length
o STEP 4: EXIT

Program:

public class CountArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//Number of elements present in an array can be found using the lengt
h
System.out.println("Number of elements present in given array: " + arr.
length);
}
}

Output:

Number of elements present in given array: 5


Next TopicJava Programs

← PrevNext →

Java Program to print the sum of all the items of the array

In this program, we need to calculate the sum of all the elements of an array.
This can be solved by looping through the array and add the value of the
element in each iteration to variable sum.

Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}
o STEP 3: SET sum = 0
o STEP 4: REPEAT STEP 5 UNTIL i<arr.length
//for(i=0; i< arr.length; i++)
o STEP 5: sum = sum + arr[i]
o STEP 6: PRINT "Sum of all the elements of an array:"
o STEP 7: PRINT sum
o STEP 8: END

Program:

public class SumOfArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
int sum = 0;
//Loop through the array to calculate sum of elements
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
}
}

Output:

Sum of all the elements of an array: 15


Next TopicJava Programs

← PrevNext →

Java Program to right rotate the elements of an array

In this program, we need to rotate the elements of array towards its right
by the specified number of times. An array is said to be right rotated if all
elements of the array are moved to its right by one position. One
approach is to loop through the array by shifting each element of the
array to its next position. The last element of the array will become the
first element of the rotated array.
Consider the above array, if n is 1 then, all elements of the array will be
moved to its right by one position that is the first element of the array
will take the second position, the second element will be moved to the
third position and so on. The last element of the array will become the
first element of the array.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] ={1, 2, 3, 4, 5 }.
o STEP 3: SET n =3
o STEP 4: PRINT "Original Array"
o STEP 5: REPEAT STEP 6 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 12 UNTIL i<n
// for(i=0; i<n; i++ )
o STEP 8: DEFINE j, last.
o STEP 9: last = arr[arr.length-1]
o STEP 10: REPEAT STEP 11 UNTIL j>0
//for(j= arr.length-1;j>0; j--)
o STEP 11: arr[j]= arr[j-1]
o STEP 12: arr[0]= last
o STEP 13: PRINT "Array after right rotation"
o STEP 14: REPEAT STEP 15 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 15: PRINT arr[i]
o STEP 16: END

Program:

class RotateRight {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//n determine the number of times an array should be rotated.
int n = 3;

//Displays original array


System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Rotate the given array by n times toward right


for(int i = 0; i < n; i++){
int j, last;
//Stores the last element of array
last = arr[arr.length-1];

for(j = arr.length-1; j > 0; j--){


//Shift element of array by one
arr[j] = arr[j-1];
}
//Last element of array will be added to the start of array.
arr[0] = last;
}
System.out.println();

//Displays resulting array after rotation


System.out.println("Array after right rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}

Output:

Original Array:
1 2 3 4 5
Array after right rotation:
3 4 5 1 2
Next TopicJava Programs

← PrevNext →

Java Program to sort the elements of an array in


ascending order

In this program, we need to sort the given array in ascending order such
that elements will be arranged from smallest to largest. This can be
achieved through two loops. The outer loop will select an element, and
inner loop allows us to compare selected element with rest of the
elements.
Elements will be sorted in such a way that the smallest element will
appear on extreme left which in this case is 1. The largest element will
appear on extreme right which in this case is 8.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
o STEP 3: SET temp =0
o STEP 4: PRINT "Elements of Original Array"
o STEP 5: REPEAT STEP 6 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length
//for(i=0; i<arr.length; i++ )
o STEP 8: REPEAT STEP 9 UNTIL j<arr.length
//for(j=i+1;j<arr.length;j++)
o STEP 9: if(arr[i]>arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
o STEP 10: PRINT new line
o STEP 11: PRINT "Elements of array sorted in ascending order"
o STEP 12: REPEAT STEP 13 UNTIL i<arr.length
//for(i=0;i<arr.length;i++)
o STEP 13: PRINT arr[i]
o STEP 14: END

Program:

public class SortAsc {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after sorting


System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8
Next TopicJava Programs

← PrevNext →

Java Program to sort the elements of an array in


descending order

In this program, we need to sort the given array in descending order


such that elements will be arranged from largest to smallest. This can be
achieved through two loops. The outer loop will select an element, and
inner loop allows us to compare selected element with rest of the
elements.

Elements will be sorted in such a way that largest element will appear on
extreme left which in this case is 8. The smallest element will appear on
extreme right which in this case is 1.

Algorithm

o STEP 1: START
o STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
o STEP 3: SET temp =0
o STEP 4: PRINT "Elements of Original Array"
o STEP 5: REPEAT STEP 6 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length
//for(i=0; i<arr.length; i++ )
o STEP 8: REPEAT STEP 9 UNTIL j<arr.length
//for(j=i+1;j<arr.length;j++)
o STEP 9: if(arr[i]<arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
o STEP 10: PRINT new line
o STEP 11: PRINT "Elements of array sorted in descending order"
o STEP 12: REPEAT STEP 13 UNTIL i<arr.length
//for(i=0;i<arr.length;i++)
o STEP 13: PRINT arr[i]
o STEP 14: END

Program:

public class SortDsc {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Sort the array in descending order
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after sorting


System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in descending order:
8 7 5 2 1
Next TopicJava Programs
Java Program to find Third Largest Number in an Array

We can find the third largest number in an array in java by sorting the
array and returning the 3nd largest number. Let's see the full example to
find the third largest number in java array.

public class ThirdLargestInArrayExample{


public static int getThirdLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-3];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Third Largest: "+getThirdLargest(a,6));
System.out.println("Third Largest: "+getThirdLargest(b,7));
}}
Test it Now

Output:

Third Largest:3
Third Largest:66

Find 3rd Largest Number in Array using Arrays

Let's see another example to get third largest element or number in java
array using Arrays.

import java.util.*;
public class ThirdLargestInArrayExample1{
public static int getThirdLargest(int[] a, int total){
Arrays.sort(a);
return a[total-3];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Third Largest: "+getThirdLargest(a,6));
System.out.println("Third Largest: "+getThirdLargest(b,7));
}}
Test it Now

Output:

Third Largest: 3
Third Largest: 66

Find 3rd Largest Number in Array using Collections

Let's see another example to get third largest number in java array using
collections.

import java.util.*;
public class ThirdLargestInArrayExample2{
public static int getThirdLargest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-3);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Third Largest: "+getThirdLargest(a,6));
System.out.println("Third Largest: "+getThirdLargest(b,7));
}}
Test it Now

Output:

Third Largest: 3
Third Largest: 66

Next Topic Java Programs

Java Program to find Second Largest Number in an Array

We can find the second largest number in an array in java by sorting the
array and returning the 2nd largest number. Let's see the full example to
find the second largest number in java array.

public class SecondLargestInArrayExample{


public static int getSecondLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}
Test it Now

Output:

Second Largest: 5
Second Largest: 77

Find 2nd Largest Number in Array using Arrays

Let's see another example to get second largest element or number in


java array using collections.

import java.util.Arrays;
public class SecondLargestInArrayExample1{
public static int getSecondLargest(int[] a, int total){
Arrays.sort(a);
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}
Test it Now

Output:

Play Video
Second Largest: 5
Second Largest: 77

Find 2nd Largest Number in Array using Collections

Let's see another example to get second largest number in java array
using collections.
import java.util.*;
public class SecondLargestInArrayExample2{
public static int getSecondLargest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-2);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}
Test it Now

Output:

Second Largest: 5
Second Largest: 77

Next Topic Java Programs

Java Program to find Largest Number in an Array

We can find the largest number in an array in java by sorting the array
and returning the largest number. Let's see the full example to find the
largest number in java array.

public class LargestInArrayExample{


public static int getLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}}
Test it Now

Output:

Largest: 6
Largest: 99

Find Largest Number in Array using Arrays

Let's see another example to get largest element in java array using
Arrays.

import java.util.Arrays;
public class LargestInArrayExample1{
public static int getLargest(int[] a, int total){
Arrays.sort(a);
return a[total-1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}}
Test it Now

Output:

Play Video
Largest: 6
Largest: 99

Find Largest Number in Array using Collections

Let's see another example to get largest number in java array using
collections.

import java.util.*;
public class LargestInArrayExample2{
public static int getLargest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-1);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}}
Test it Now

Output:

Largest: 6
Largest: 99
Next Topic Java Programs

Java Program to find Second Smallest Number in an Array

We can find the second smallest number in an array in java by sorting


the array and returning the 2nd element. Let's see the full example to
find the second smallest number in java array.

public class SecondSmallestInArrayExample{


public static int getSecondSmallest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[1];//2nd element because index starts from 0
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second smallest: "+getSecondSmallest(a,6));
System.out.println("Second smallest: "+getSecondSmallest(b,7));
}}
Test it Now

Output:
Second smallest: 2
Second smallest: 33

Find 2nd Smallest Number in Array using Arrays

Let's see another example to get second smallest element or number in


java array using Arrays.

import java.util.*;
public class SecondSmallestInArrayExample1{
public static int getSecondSmallest(int[] a, int total){
Arrays.sort(a);
return a[1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Smallest: "+getSecondSmallest(a,6));
System.out.println("Second Smallest: "+getSecondSmallest(b,7));
}}
Test it Now

Output:

Play Video
Second smallest: 2
Second smallest: 33

Find 2nd Smallest Number in Array using Collections

Let's see another example to get second smallest number in java array
using collections.

import java.util.*;
public class SecondSmallestInArrayExample2{
public static int getSecondSmallest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(1);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Second Smallest: "+getSecondSmallest(a,6));
System.out.println("Second Smallest: "+getSecondSmallest(b,7));
}}
Test it Now

Output:

Second smallest: 2
Second smallest: 33

Next Topic Java Programs

Java Program to find Smallest Number in an Array

We can find the smallest element or number in an array in java by


sorting the array and returning the 1st element. Let's see the full example
to find the smallest number in java array.

public class SmallestInArrayExample{


public static int getSmallest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[0];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Smallest: "+getSmallest(a,6));
System.out.println("Smallest: "+getSmallest(b,7));
}}
Test it Now

Output:

Smallest: 1
Smallest: 22

Find Smallest Number in Array using Arrays

Let's see another example to get the smallest element or number in java
array using Arrays.

import java.util.*;
public class SmallestInArrayExample1{
public static int getSmallest(int[] a, int total){
Arrays.sort(a);
return a[0];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Smallest: "+getSmallest(a,6));
System.out.println("Smallest: "+getSmallest(b,7));
}}
Test it Now

Output:

Smallest: 1
Smallest: 22

Find Smallest Number in Array using Collections

Let's see another example to get smallest number in java array using
collections.

import java.util.*;
public class SmallestInArrayExample2{
public static int getSmallest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(0);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Smallest: "+getSmallest(a,6));
System.out.println("Smallest: "+getSmallest(b,7));
}}
Test it Now

Output:

Smallest: 1
Smallest: 22

Next Topic Java Programs

← PrevNext →
Java Program to remove duplicate element in an Array

We can remove duplicate element in an array by 2 ways: using


temporary array or using separate index. To remove the duplicate
element from array, the array must be in sorted order. If array is not
sorted, you can sort it by calling Arrays.sort(arr) method.

1) Remove Duplicate Element in Array using Temporary


Array

public class RemoveDuplicateInArrayExample{


public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}

public static void main (String[] args) {


int arr[] = {10,20,20,30,30,40,50,50};
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
Test it Now

Output:

10 20 30 40 50

2) Remove Duplicate Element in Array using separate


index

public class RemoveDuplicateInArrayExample2{


public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int j = 0;//for next element
for (int i=0; i < n-1; i++){
if (arr[i] != arr[i+1]){
arr[j++] = arr[i];
}
}
arr[j++] = arr[n-1];
return j;
}

public static void main (String[] args) {


int arr[] = {10,20,20,30,30,40,50,50};
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
Test it Now

Output:

10 20 30 40 50

Remove Duplicate Elements in Unsorted Array

If you have unsorted array, you need to sort it first. To do so, use
Arrays.sort(arr) method.

Play Video

import java.util.Arrays;
public class RemoveDuplicateInArrayExample3{
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args) {
int arr[] = {10,70,30,90,20,20,30,40,70,50};//unsorted array
Arrays.sort(arr);//sorting array
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
Test it Now

Output:

10 20 30 40 50 70 90

Next Topic Java Programs

Java Program to print Odd and Even Numbers from an


Array

We can print odd and even numbers from an array in java by getting
remainder of each element and checking if it is divided by 2 or not. If it is
divided by 2, it is even number otherwise it is odd number.

public class OddEvenInArrayExample{


public static void main(String args[]){
int a[]={1,2,5,6,3,2};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++){
if(a[i]%2!=0){
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++){
if(a[i]%2==0){
System.out.println(a[i]);
}
}
}}
Test it Now

Output:

Odd Numbers:
1
5
3
Even Numbers:
2
6
2

How to Sort an Array in Java

The sorting is a way to arrange elements of a list or array in a certain


order. The order may be in ascending or descending order.
The numerical and lexicographical (alphabetical) order is a widely used
order.

In this section, we will learn how to sort


array in Java in ascending and descending order using
the sort() method and without using the sort() method. Along with
this, we will also learn how to sort subarray in Java.

Sort Array in Ascending Order

The ascending order arranges the elements in the lowest to highest


order. It is also known as natural order or numerical order. We can
perform sorting in the following ways:

o Using the sort() Method


o Without using the method
o Using the for Loop
o Using the User Defined Method

Using the sort() Method

In Java, Arrays is the class defined in the java.util package that


provides sort() method to sort an array in ascending order. It uses Dual-
Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is
a static method that parses an array as a parameter and does not return
anything. We can invoke it directly using the class name. It accepts an
array of type int, float, double, long, char, byte.

Play Video

Syntax:

1. public static void sort(int[] a)

Where a is an array to be short.

Note: Like the Arrays class, the Collections class also provides the sort()
method to sort the array. But there is a difference between them. The
sort() method of the Arrays class works for primitive type while the sort()
method of the Collections class works for objects Collections, such as
LinkedList, ArrayList, etc.

Let's sort an array using the sort() method of the Arrays class.

In the following program, we have defined an array of type integer. After


that, we have invoked the sort() method of the Arrays class and parses
the array to be sort. For printing the sorted array, we have used for loop.

SortArrayExample1.java

import java.util.Arrays;
public class SortArrayExample1
{
public static void main(String[] args)
{
//defining an array of integer type
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
//invoking sort() method of the Arrays class
Arrays.sort(array);
System.out.println("Elements of array sorted in ascending order: ");
//prints array using the for loop
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
}

Output:

Array elements in ascending order:


5
12
22
23
34
67
90
109

In the above program, we can also use the toSting() method of


the Arrays class to print the array, as shown in the following statement. It
returns a string representation of the specified array.

1. System.out.printf(Arrays.toString(array));

Without Using the Method

Using the for Loop

In the following example, we have initialized an array of integer type and


sort the array in ascending order.

SortArrayExample2.java
public class SortArrayExample2
{
public static void main(String[] args)
{
//creating an instance of an array
int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};
System.out.println("Array elements after sorting:");
//sorting logic
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
int tmp = 0;
if (arr[i] > arr[j])
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
//prints the sorted element of the array
System.out.println(arr[i]);
}
}
}

Output:

Array elements after sorting:


-65
-4
-1
1
3
6
20
34
34
55
78
90

Using the User Defined Method

In the following example, we have defined a method


named sortArray() that contains the logic to sort an array in natural
order.

SortArrayExample3.java

public class SortArrayExample3


{
public static void main(String[] args)
{
int i;
//initializing an array
int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27};
System.out.print("Array elements before sorting: \n");
for(i = 0; i < array.length; i++)
System.out.println(array[i]);
//invoking user defined method
sortArray(array, array.length);
System.out.print("Array elements after sorting: \n");
//accessing elements of the sorted array
for(i = 0; i <array.length; i++)
{
System.out.println(array[i]);
}
}
//user defined method to sort an array in ascending order
private static void sortArray(int array[], int n)
{
for (int i = 1; i < n; i++)
{
int j = i;
int a = array[i];
while ((j > 0) && (array[j-1] > a)) //returns true when both conditions are t
rue
{
array[j] = array[j-1];
j--;
}
array[j] = a;
}
}
}

Output:

Array elements before sorting:


12
45
1
-1
0
4
56
23
89
-21
56
27
Array elements after sorting:
-21
-1
0
1
4
12
23
27
45
56
56
89

Sort Array in Descending Order

The descending order arranges the elements in the highest to lowest


order. We can perform sorting in the following ways:

o Using the reverseOrder() Method


o Without using the method
o Using the for Loop
o Using the User Defined Method

Using the reverseOrder() Method

Java Collections class provides the reverseOrder() method to sort the


array in reverse-lexicographic order. It is a static method, so we can
invoke it directly by using the class name. It does not parse any
parameter. It returns a comparator that imposes the reverse of the
natural ordering (ascending order).

It means that the array sorts elements in the ascending order by using
the sort() method, after that the reverseOrder() method reverses the
natural ordering, and we get the sorted array in descending order.

Syntax:

1. public static <T> Comparator<T> reverseOrder()

Suppose, a[] is an array to be sort in the descending order. We will use


the reverseOrder() method in the following way:

1. Arrays.sort(a, Collections.reverseOrder());

Let's sorts an array in the descending order.


In the following program, a point to be noticed that we have defined an
array as Integer. Because the reverseOrder() method does not work for
the primitive data type.

SortArrayExample4.java

import java.util.Arrays;
import java.util.Collections;
public class SortArrayExample4
{
public static void main(String[] args)
{
Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205};
// sorts array[] in descending order
Arrays.sort(array, Collections.reverseOrder());
System.out.println("Array elements in descending order: " +Arrays.toString(
array));
}
}

Output:

Array elements in descending order: [205, 110, 102,


78, 23, 11, 6, 4, 0, -1, -9]

Let's see another program that sorts array elements in alphabetical


order.

SortArrayExample5.java

import java.util.Arrays;
import java.util.Collections;
public class SortArrayExample5
{
public static void main(String[] args)
{
String [] strarray = {"Mango", "Apple", "Grapes", "Papaya", "Pineapple", "Ban
ana", "Orange"};
// sorts array[] in descending order
Arrays.sort(strarray, Collections.reverseOrder());
System.out.println("Array elements in descending order: " +Arrays.toString(s
trarray));
}
}

Output:

Array elements in descending order: [Papaya,


Pineapple, Orange, Mango, Grapes, Banana, Apple]

Without Using the Method

Using the for Loop

In the following example, we have initialized an integer array and


perform sorting in descending order.

SortArrayExample6.java

public class SortArrayExample6


{
public static void main(String[] args)
{
int temp;
//initializing an array
int a[]={12,5,56,-2,32,2,-26,9,43,94,-78};
for (int i = 0; i < a.length; i++)
{
for (int j = i + 1; j < a.length; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Array elements in descending order:");
//accessing element of the array
for (int i = 0; i <=a.length - 1; i++)
{
System.out.println(a[i]);
}
}
}

Output:

Array elements in descending order:


94
56
43
32
12
9
5
2
-2
-26
-78

Using the User Defined Method

SortArrayExample7.java

import java.util.Scanner;
public class SortArrayExample7
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Array elements in descending order:");
for (int i = 0; i < n - 1; i++)
{
System.out.println(a[i]);
}
System.out.print(a[n - 1]);
}
}

Output:
Enter the number of elements: 7
Enter the elements of the array:
12
5
56
-2
32
2
-26
Array elements in descending order:
56
32
12
5
2
-2
-26

How to Sort Subarray

An array derived from the array is known as subarray. Suppose, a[] is an


array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want
to sort array elements from 34 to 18. It will sort the subarray [34, 2, 45,
3, 22, 18] and keep the other elements as it is.

To sort the subarray, the Arrays class provides the static method
named sort(). It sorts the specified range of the array into ascending
order. We can also sort the array of type long, double, float, char,
byte, etc.

Syntax:

1. public static void sort(int[] a, int fromIndex, int toIndex)

The method parses the following three parameters:

o a: An array to be sort.
o fromIndex: The index of the first element of the subarray. It
participates in the sorting.
o toIndex: The index of the last element of the subarray. It does not
participate in the sorting.

If formIndex is equal to the toIndex, the range to be sorted is empty. It


throws IllegalArgumentException if fomIndex is greater than toIndex.
It also throws ArrayIndexOutOfBoundsException if fromIndex < 0 or
toIndex > a.length.

Let's sort a subarray through a Java program.

SortSubarrayExample.java

import java.util.Arrays;
public class SortSubarrayExample
{
public static void main(String[] args)
{
//defining an array
int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78};
// sorts subarray form index 2 to 7
Arrays.sort(a, 2, 7);
//prints array using the for loop
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i]);
}
}
}

Output:

Sorted Subarray:
12
90
2
3
22
34
45
18
5
78

Next Topic Java Tutorial

You might also like