Как использовать пузырьковую сортировку для сортировки многомерного массива в Java - PullRequest
0 голосов
/ 11 декабря 2018

Вот викторина, которую я создал, основанная на спорте, которая задает серию вопросов, где у пользователя есть 3 попытки каждый раз.Оттуда он суммирует счет каждого игрока и показывает его в виде двумерного массива, сравнивает результаты и выводит наивысший результат.Как бы я использовал пузырьковую сортировку (не array.sort) для сортировки 2-го массива (табло) по второму индексу (счету).

import java.util.*;

class miniproj
{
  public static void main(String[] args)
  {
    Questions[] questions = setQuestions(); // store array of questions using setquestions method
    askQuestion(questions); // run method askquestion using questions parameter (array)
  }

  public static Questions[] setQuestions()
  {
   Questions[] questions = new Questions[4]; //create array of type questions
    Questions A = new Questions(); // create new questons type called A
    A.question = "What team won the world cup in 1966?";
    A.options = " A. Germany\n B. France\n C. England\n D. Wales";
    A.answer = "C";
    questions[0] =  A; // the first question in the aray is A

    Questions B = new Questions();
    B.question = "Who are the current EPL title holders?";
    B.options = " A. Arsenal\n B. Bournemouth\n C. Chelsea\n D. Manchester City";
    B.answer = "D";
    questions[1] =  B;

    Questions C = new Questions();
    C.question = "Who is the current Golden Boot holder 2017/18 season?";
    C.options = " A. Lionel Messi\n B. Harry Kane\n C. Cristiano Ronaldo\n D. Davidson Sanchez";
    C.answer = "A";
    questions[2] =  C;

    Questions D = new Questions();
    D.question = "Which team has most goals";
    D.options = " A. Arsenal\n B. Bournemouth\n C. Chelsea\n D. Manchester City";
    D.answer = "A";
    questions[3] =  D;

    return questions; // return array of questions
  }

  public static void askQuestion(Questions[] array)
  {
    int correct = 0;
    Scanner sc = new Scanner(System.in);
    String[][] scoreboard = new String[4][2];



    for(int m = 0; m < scoreboard.length; m++) {
      correct = 0;
      System.out.println("What is your name");
      scoreboard[m][0] = sc.nextLine();



        for(int i = 0; i < 4; i ++) // this loops for all four questions
        {

            for(int k = 4; k > 1; k --)
            {
                System.out.println(array[i].question);
                System.out.println(array[i].options);
                String answer = sc.nextLine();

                if(answer.equalsIgnoreCase(array[i].answer)) // this loops til correct answer is given
                {
                  System.out.println("Correct");
                  correct = correct + 1;
                  break;
                }
                else
                {
                  System.out.println("Incorrect, you have " + (k - 2) + " tries left");
                }
            }

        }  

         scoreboard[m][1] = Integer.toString(correct);
         System.out.println(correct + "  questions correct");

    }


    int mostCorrectIndex = 0;

    for (int c = 1; c < scoreboard.length; c++) {
        if (Integer.parseInt(scoreboard[c][1]) > Integer.parseInt(scoreboard[mostCorrectIndex][1]))
            mostCorrectIndex = c;
} 
      System.out.println("The person with the highest score is " + scoreboard[mostCorrectIndex][0]);
      for (int b = 0; b < scoreboard.length; b++) {
        System.out.println(Arrays.toString(scoreboard[b]));
      }
    }
}
class Questions
{
  String question;
  String options;
  String answer;
}

Ответы [ 2 ]

0 голосов
/ 11 декабря 2018

В этом контексте вы можете реализовать пузырьковую сортировку с модификацией для сравнения значимых значений.Пример:

static void bubbleSort(String[][] arr) {
        int arrayLength = arr.length;
        for (int i = 0; i < arrayLength; i++) {
            for (int j = 1; j < (arrayLength - i); j++) {
                String nameTemp, scoreTemp;
                int leftValue, rightValue;
                leftValue = Integer.valueOf(arr[j - 1][1]);
                rightValue = Integer.valueOf(arr[j][1]);
                if (leftValue > rightValue) {
                    //swap elements
                    nameTemp = arr[j - 1][0];
                    scoreTemp = arr[j - 1][1];
                    arr[j - 1][0] = arr[j][0];
                    arr[j - 1][1] = arr[j][1];
                    arr[j][0] = nameTemp;
                    arr[j][1] = scoreTemp;
                }

            }
        }
}

И тогда вам нужен последний индекс массива, поскольку он отсортирован по возрастанию.

0 голосов
/ 11 декабря 2018

Если я правильно вас понимаю, у вас есть 2d структура массива, подобная этой:

{name,score}
{name,score}
{name,score}
{name,score}

, и вы хотите отсортировать по второму столбцу: Score.

Вместо реализацииэто в двумерном массиве, почему бы вам не создать объект с именем Player

, где у Player есть реализация:

public class Player{

    private String name;
    private int score;        

    Player(String name){
        this.name = name;
    }

    public void setScore(int score){
        this.score = score;
    }

    public int getScore(){
        return score;
    }
}

Теперь ваше табло теперь может быть реализовано в размерный массив примерно так:

Player[] scoreboard = new Player[playerSize];

Намного проще понять и прочитать.

Теперь, чтобы отсортировать этот массив, вы можете реализовать собственный класс, который позволяет сравнивать два объекта:введите Player

class comparePlayer implements Comparator<Player>{

    public int compare(Player a, Player b) {
        if (a.getScore() < b.getScore()){
            return -1;
        }
        else if (a.getScore() == b.getScore()){
            return 0;
        }
        else{
            return 1;
        }
    }

}

Теперь вы можете сортировать по баллам следующим образом ->

Arrays.sort(scoreboard,new comparePlayer());

Или, если вы действительно хотите использовать пузырьковую сортировку, вы можете реализовать это следующим образом:

int length = scoreboard.length; 
for (int i = 0; i < length-1; i++){ 
    for (int j = 0; j < length-i-1; j++){ 
        if (scoreboard[j].getScore() > scoreboard[j+1].getScore()){ 
            Player temp = scoreboard[j]; 
            scoreboard[j] = scoreboard[j+1]; 
            scoreboard[j+1] = temp; 
        } 
    }
}
...