如何用Java排序数据

时间:2018-08-28 00:17:22

标签: java sorting

我想根据关键字值的数量对数据进行排序,如果它们是相同的关键字值,那么我将根据单词数对它们再次进行排序。

keywordword之间的每个索引都是相关的。 keyword中的索引0对应于word中的索引0。

输入:

keyword = {1,0,2,0,2}
word = {6,0,2,0,3}

输出将是:

keyword = {2, 2, 1, 0, 0}
word = {3, 2, 6, 0, 0}

我试图创建一个像这样的程序,但是输出不合适。如何正确排序?

public static void sortAnswer(List<Integer> word, List<String> getDoc, List<Integer> keyOccurence){
    int[] totalWord = new int[word.size()] ;
    int[] mDoc = new int[word.size()];
    int[] totalKey = new int[word.size()];
    int g = 0;
    int k = 0;
    int i = 0;

    for (int d = 0; d < word.size(); d++) {
        totalWord[k] = word.get(d);
        mDoc[k] = g;
        totalKey[k] = keyOccurence.get(d);
        k++;
        g++;
    }   

    int temp = 0;
    int t = 0;  
    int te = 0;      
    for(i = 0; i < word.size()-1; i ++)
    {
        for(int p=1; p<word.size(); p++)
        {
            if(totalKey[p-1] < totalKey[p])
            {
                temp = totalWord[p-1];
                t = mDoc[p-1];
                te = totalKey[p-1];

                totalWord[p-1] = totalWord[p];
                mDoc[p-1] = mDoc[p];
                totalKey[p-1] = totalKey[p];

                totalWord[p] = temp;
                mDoc[p] = t;
                totalKey[p] = te;
            }
        }
    }

    //Sorting the highest number of words
    g = 0;
    k = 0;
    i = 0;
    for (int d = 0; d < word.size(); d++) {
        totalWord[k] = word.get(d);
        mDoc[k] = g;
        totalKey[k] = keyOccurence.get(d);
        k++;
        g++;
    }   

    temp = 0;
    t = 0;  
    te = 0;
    for(i = 0; i < word.size()-1; i ++)
    {
        for(int p=1; p<word.size(); p++)
        {
            if (totalKey[p-1] == totalKey[p]) 
            {   
                if(totalWord[p-1] < totalWord[p]) {
                    temp = totalWord[p-1];
                    t = mDoc[p-1];
                    te = totalKey[p-1];

                    totalWord[p-1] = totalWord[p];
                    mDoc[p-1] = mDoc[p];
                    totalKey[p-1] = totalKey[p];

                    totalWord[p] = temp;
                    mDoc[p] = t;
                    totalKey[p] = te;
                }            
            }
        }
    }

    int f = 0;
    for(i = 0; i < word.size(); i++)
    {
        f = mDoc[i];
        System.out.print("Total Key : "+totalKey[i]);
        System.out.println(" == Total Word : " +totalWord[i]);
        System.out.println("Document : " +getDoc.get(f));
        f++;
    }   

    System.out.println("\nValid Answer"); 
    f = mDoc[0];   
    String answer = getDoc.get(f);
    System.out.println(answer);

0 个答案:

没有答案