Array Basics - 2
Array Basics - 2
Step 1: Initialize integer variable for storing maximum Element (int max;)
Step 3: Compare max with each and every array element, this can be achieved
using for loop and If statement .
For Example: Except the ‘5’ in the given Array is to be copied in the new array
with the reduced length.
int[] array={5,88,99,5,1,7}
int count=0;// for storing number of ‘5’ in given array
for(int i=0;i<array.length;i++){
if(array[i]==5)
count++;
}
int resultlength=array.length-count;// Result array length
int[] result=new int[resultlength];// initializing result array
int k=0;// pointer for result array
for(int i=0;i<array.length;i++){
if(array[i]!=5){
result[k]=array[i];
k++;}
System.out.println(result[k]+”,”);
}
Sorting:
Ascending order:
{5,6,1,3}
Sorting as follows
Each element should be compared with the other elements an interchange the
positions. So it can be achieved using two for loop as follows.
First element in the array is 5 is compared with all array elements as
If any array element is less then the array element are exchanged.
int[] array={5,6,1,3}
int temp=0;
for(int i=0;i<array.length;i++){// one element is taken
for(int k=i;k<array.length;k++) { //from that element the comparison is
started till the end length
if(array[i]>array[k]){
temp=array[i];
array[i]=array[k];
array[k]=temp;
}
}