Sunday, April 28, 2024

Sort an array and display the elements in descending order along with its original index

This is a BlueJ Program where the elements of an array will be displayed in descending order and the original index of the elements will also be displayed.

In this program, two numeric arrays are used - one to store the elements and the other to store the original index of the elements.

import java.util.*;
class Arrange
{
    int i,j,temp,n;
    int arr[],arrindex[];
    Scanner sc=new Scanner(System.in);
public void takeValues()
{    
    System.out.print("\nHow many elements to store: ");
     n=sc.nextInt();
     arr=new int[n];
     arrindex=new int [n];
     for(i=0;i< n;i++)
     {
          System.out.print("\nValue: ");
          arr[i]=sc.nextInt();
          arrindex[i]=i; // storing the index of the entered value
     }
 }
    public void showValues()

    {
        System.out.println("\nEntered Value");
        for(i=0;i< n;i++)
        System.out.print(" "+arr[i]);
        for(i=0;i< n-1;i++)
        {
             for(j=i+1;j< n;j++)
             {
                 if(arr[i]< arr[j])
                 {
                      temp=arr[i];
                      arr[i]=arr[j];
                      arr[j]=temp;
                      // Values Interchanged
                      temp=arrindex[i];
                      arrindex[i]=arrindex[j];
                      arrindex[j]=temp;
                      // indexes Interchanged
                    }
                }
            }
        System.out.println("\nSorted Elements with Original Indexes");
        for(i=0;i< n;i++)
        System.out.println(arr[i] + " " + arrindex[i]);
    }
      
    public static void main(String args[])
    {
        Arrange ob=new Arrange();
        ob.takeValues();
        ob.showValues();
   }
 }


Related Post: BlueJ Programs on Numeric Array

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner