Java Bucket排序字符串

时间:2010-03-31 00:55:39

标签: java sorting arraylist bucket

我无法弄清楚使用Bucket Sort来排序总长度相同的字符串列表的最佳方法。

算法如下所示:

For the last character position down to the first:
    For each word in the list:
        Place the word into the appropriate bucket by current character
    For each of the 26 buckets(arraylists)
        Copy every word back to the list

我正在用java编写,我正在使用arraylist作为存储未排序字符串的主列表。每个字符串长度为五个字符。

这就是我的开始。它只是在第二个循环中停止,因为我不知道接下来该做什么或者我是否做了第一部分。

ArrayList<String> count = new ArrayList<String>(26);

for (int i = wordlen; i > 0; i--) {
    for (int j = 0; i < myList.size(); i++)
        myList.get(j).charAt(i)
}

提前致谢。

编辑:这就是我现在所拥有的。我知道它不起作用,因为如果有多个字符串以相同的字母开头而不是它会爆炸,但我认为我的方向更正确。当我运行它时,即使用我放入的单词来确保没有重复字母,它在第一个设置行上吓坏了:count.set(myList.get(j).charAt(i), myList.get(j));它说“线程中的异常”主“java.lang.StringIndexOutOfBoundsException :字符串索引超出范围:5“

 public void BucketSort(int wordlen) {

   ArrayList<String> count = new ArrayList<String>(26);

     //Make it so count has a size
   for(int p = 0; p < 26; p++)
       count.add(null);

    for (int i = wordlen; i > 0; i--) { //for each letter
        for (int j = 0; j < myList.size(); j++) //for each word
               //Add the word to count based on the letter
            count.add((int)myList.get(j).charAt(i) - 65, myList.get(j));
}
     //Clear the main list so there aren't a bunch of unsorted words leftover
   myList.clear();

     //Add the words back in to the list based on their order in count
   for (int m = 0; m < 26; m++)
       myList.add(count.get(m));
  }

4 个答案:

答案 0 :(得分:3)

这看起来像是我的作业,所以我不会回答代码解决方案。

但基本上,你坚持的一点就是设置你的桶。可能你想要你的桶是Map<Character, List<String>> - 也就是说,你想要将每个字母A - Z映射到与该字母匹配的单词列表(对于你当前正在查看的位置)。那个单词列表就是你的桶。

然后,在完成内部循环之后,你已经到了那里,你在地图内容中再做一次循环,从AZ(提示:for ( char ch = 'A'; ch <= 'Z'; ch++ ))开始,并将相应桶的内容转储回你的(清空)清单。

答案 1 :(得分:1)

在一个小清单上测试过;是的,我还必须为家庭作业做这件事,为了方便你留下评论,这样你才能理解发生了什么,而不仅仅是复制粘贴(如果你这样做,你的OV分数将是100%!)。

public static void sort(String[] array) {
        if (array.length == 0) return;  // empty check

        // Determine max length
        int max = 0;
        for (int i = 1; i < array.length; i++) {
            // update max length
            if (max < array[i].length()) max = array[i].length();
        }


        // Initialize buckets
        int bucketCount = 26;   // alphabet
        // buckets in maps
        HashMap<Character, Vector<String>> buckets = new HashMap<Character, Vector<String>>(bucketCount);
        // create the buckets
        char a = 'a';
        for (int i = 0; i <= bucketCount; i++, a++){
            buckets.put(a, new Vector<String>());
        }   

        // assign array values into buckets
        for (int i = 0; i < array.length; i++) {
            // get first letter of word
            String current = array[i];
            char letter = current.toLowerCase().charAt(0);
            buckets.get(letter).add(array[i]);
        }

        // Sort buckets and place back into input array
        int index = 0;  // keeps global array index
        for (char key = 'a'; key <= 'z'; key++) {
            // retrieve the bucker
            Vector<String> bucket = buckets.get(key);

            // do an insertion sort on bucket
            for (int i = 1; i < bucket.size(); i++){
                // i starts as 1, as a list of size 1 is already sorted

                // save the value at the index and remove it
                String temp = bucket.get(i);
                bucket.remove(i);

                // move all values one up, until we find the saved value's location
                int j;
                for(j = i-1; j >= 0 && 
                        bucket.get(j).compareToIgnoreCase(temp) > 0; j--){
                    // to "insert", we need to add and remove
                    bucket.add(j+1, bucket.get(j));
                    bucket.remove(j);
                }
                // place the saved value in the proper location
                bucket.add(j+1, temp);
            }


            // pile the current bucket back into array
            for (int j = 0; j < bucket.size(); j++) {
                array[index++] = bucket.get(j);
            }
        }
    }

答案 2 :(得分:0)

如果您不打算使用Map,则可以使用@JacobM所描述的相同逻辑,但改为使用List数组。所以你创建了List<String>[] buckets = new List<String>[26]

答案 3 :(得分:0)

public void bucketSort(String[] words)
{

    int maxlength=0;
    for(int i=0;i<words.length;i++)
    {
        words[i] = words[i].toUpperCase();
        if(maxlength<words[i].length())
            maxlength = words[i].length();

    }

    for(int j=maxlength-1;j>=0;j--)
    {

        Vector<Vector<String>> map = new Vector<Vector<String>>();
        for(int i=0;i<27;i++)
        {
            map.add(null);
        }
        for(int i=0;i<words.length;i++)//Add words of of length j or greater to map(which is bucket here)
        {

            if(words[i].length()>j)
            {
                int val = (int)words[i].charAt(j) -65;
                if(map.get(val)!= null)
                {
                    map.get(val).add(words[i]);
                }
                else
                {
                    Vector<String> vecot = new Vector<String>();
                    vecot.add(words[i]);
                    map.add(val, vecot);
                }
            }
            else///Add words of of length<j to bucket 0
            {
                if(map.get(0) != null)
                {
                    map.get(0).add(words[i]);
                }
                else
                {
                    Vector<String> vecot = new Vector<String>();
                    vecot.add(words[i]);
                    map.add(0, vecot);
                }

            }
        }
        int count =0;
        for(int i=0;i<map.size();i++)
        {

            if(map.get(i)!=null)
            {
                for(int k=0;k<map.get(i).size();k++)
                {
                 words[count]=map.get(i).get(k); 
                 count++;
                }
            }
        }
        System.out.println("Next set :");
        for(int i=0;i<words.length;i++)
        {
            System.out.println(words[i]);
        }

    }




}