write an algorithm or a java program to complete the given task.
problem:
for example consider an array of elements 1,4,3,8,22,10 .Now you have to sort the array in a way that its even postioned values will be in decreasing order ,its odd positined values must be in increasing order .For given problem the solution will be 1 22 3 10 4 8 .
solution:
//algoritm written by shashi kumar
import java.util.Arrays;
public class TecnicsProgram {
public static void main(String args[])
{
//given data is 1,4,3,8,22,10
int givenData[]={1,4,3,8,22,10};
//sort the data next from given arry of data
Arrays.sort(givenData);
//check weather data is sorted or not
/*for(int i=0;i<givenData.length;i++)
{
System.out.print(givenData[i]+" ");
}
*/
//now take first index and last index values of givenData
int firstIndex=0,lastIndex=givenData.length-1;
//define a new arry for result
int res[]=new int[givenData.length];
for(int index=0;index<givenData.length;index++)
{
//loop through each and every element of given array
if(index%2==0)
{
//even position so put min element
if(firstIndex>lastIndex)
break;
res[index]=givenData[firstIndex];
firstIndex++;
}
else
{
//it is an even index so put max element
if(lastIndex<firstIndex)
break;
res[index]=givenData[lastIndex];
lastIndex--;
}
}
//now print res array
for(int x=0;x<res.length;x++)
{
System.out.print(res[x]+" ");
}
}
}
problem:
for example consider an array of elements 1,4,3,8,22,10 .Now you have to sort the array in a way that its even postioned values will be in decreasing order ,its odd positined values must be in increasing order .For given problem the solution will be 1 22 3 10 4 8 .
solution:
//algoritm written by shashi kumar
import java.util.Arrays;
public class TecnicsProgram {
public static void main(String args[])
{
//given data is 1,4,3,8,22,10
int givenData[]={1,4,3,8,22,10};
//sort the data next from given arry of data
Arrays.sort(givenData);
//check weather data is sorted or not
/*for(int i=0;i<givenData.length;i++)
{
System.out.print(givenData[i]+" ");
}
*/
//now take first index and last index values of givenData
int firstIndex=0,lastIndex=givenData.length-1;
//define a new arry for result
int res[]=new int[givenData.length];
for(int index=0;index<givenData.length;index++)
{
//loop through each and every element of given array
if(index%2==0)
{
//even position so put min element
if(firstIndex>lastIndex)
break;
res[index]=givenData[firstIndex];
firstIndex++;
}
else
{
//it is an even index so put max element
if(lastIndex<firstIndex)
break;
res[index]=givenData[lastIndex];
lastIndex--;
}
}
//now print res array
for(int x=0;x<res.length;x++)
{
System.out.print(res[x]+" ");
}
}
}
output:
1 22 3 10 4 8
Không có nhận xét nào:
Đăng nhận xét