Java Program to sort the elements of an array in ascending order and descending order
In this program, we need to compaire each elemrnt of the given array to each element adding each other and thorugh out the addition of the given array is . This can be accomplished by looping through the array and store the elements of the array at the corresponding position.
Original array
1,22,13,5,50
ascending oder :-
1 5 13 22 50
descending oder :-
50 22 12 5 1
Algorithm
- 1.START
- 2.INITIALIZE arr1[] ={1,2,3,4,5}
- 3.i=a.lenght;i>0,i--
- 4.int j=i+1;j< arr.length;j++
- 5. arr[i] < arr[j] // asceding
- 6.swap
- 7. arr[i] > arr[j] //descending
- 8. swap
- 4.display of array
Program
class Q8_ascending_descending {
public static void main(String[] args)
//declare array
int arr[]={11,2,33,45,59};
System.out.println("original array is");
for(int i=0;i< arr.length;i++)
{
System.out.print(arr[i] + " ");
}
//descending array
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;
}
}
}
//display descending oder array
System.out.println("after Descending order");
for(int i=0;i< arr.length;i++)
{
System.out.print(arr[i] + " ");
}
//ascending array
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;
}
}
}
//display ascending oder array
System.out.println("after ascending order");
for(int i=0;i< arr.length;i++)
{
System.out.print(arr[i] + " ");
}
output
Original array
1,22,13,5,50
ascending oder :-
1 5 13 22 50
descending oder :-
50 22 12 5 1
Next Topic
No comments:
Post a Comment