S
S
Sergey Saifulin2015-03-17 15:37:55
Java
Sergey Saifulin, 2015-03-17 15:37:55

How to output array indices in descending order of elements in Java?

Hello.
You need to print the indices of an integer array in descending order of their corresponding elements.
Wrote the following code. Doesn't work because the elements are not swapped. Can you tell me how to fix it?
If you can suggest a more elegant solution, I'd appreciate it.

import java.io.IOException;
import java.util.Scanner;

public class Zadacha1 {

  public static void main(String[] args) throws IOException {
    
    Zadacha1 example = new Zadacha1();
    example.recieving();
    example.sorting();
  }

  Scanner scan = new Scanner(System.in);
  int[] Array = new int[7];
  
  //заполнение массива
  public void recieving(){
    
    for (int i = 0; i < Array.length; i++){
      System.out.println("Input next element: ");
      Array[i] = scan.nextInt();
    }
  }
  
  //сортировка массива и заполнение массива индексов
  public void sorting(){
    int[][] All = new int[2][Array.length];
    for (int i = 0; i < Array.length; i++){
      All[0][i] = i;
      All[1][i] = Array[i];
    }
    for (int i = 0; i < Array.length; i++){
      for (int j = i; j < Array.length; j++){
        if (All[1][j] > All[1][i]){
          swap(All[0][i], All[0][j]);
          swap(All[1][i], All[1][j]);
        }
      }
    }
    for (int i = 0; i < Array.length; i++){
      System.out.print(All[0][i] + " ");
    }
  }


  //перемена мест
  public void swap(int a, int b){
    int c = a;
    a = b;
    b = c;
  }
  
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
anyd3v, 2015-03-17
@anyd3v

//перемена мест
  public void swap(int a, int b){
    int c = a;
    a = b;
    b = c;
  }

Do you understand what's going on here?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question