Wednesday, September 4, 2019

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 but the original index of the elements will also be displayed.



import java.util.*;
class Search
{
    int i,j,temp,n;
    int arr[],arrindex[];
    Scanner sc=new Scanner(System.in);
public void take()
{    
    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 show()


    {
        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[])
    {
        Search ob=new Search();
        ob.take();
        ob.show();
   }
 }


Related Post: BlueJ Programs on Numeric Array

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner