コード例 #1
0
ファイル: Program.cs プロジェクト: Sabashan-Ragavan/qlabs
        //The below function is my implementation for question 2. 
        //
        //:p is the size of the lexicographical order, 
        //:n is the number of strings in the string array,
        //:m is the size of the strings
        //
        //Run-Time: F(n) = p+n*(m+logn)= O(n*logn) or O(n*m) depending if logn > m or m > logn and noting that p can be at maximum, 
        //the size of the alphabet, and thus essentially a constant, 
        //
        public static String[] Sort(String[] un_sorted, string order)
        {
            Dictionary<string, int> priority = new Dictionary<string, int>();
            BST string_score = new BST();

            //iterate through every charcter in the user-specified lexicographical ordering 
            //assign a priority to each character corresponding to their index in the string+1
            priority.Add(" ", 0); 
            for (int i = 0; i < order.Length; i++) //O(p)
            {
                priority.Add(order[i].ToString(), i + 1);
            }

            for (int i = 0; i < un_sorted.Length; i++) //O(n)
            {
                string word = un_sorted[i];
                if (word != null) 
                {
                    double score = -1.0;
                    if (word.Length > 0)
                    {
                        score = 0.0;
                        //Calculate a score similar to calculting the value of a base N character array
                        //In this case, our N would be order.Length + 1 
                        for (int j = 0; j < word.Length; j++) //O(m)
                        {
                            if (priority.ContainsKey(word[j].ToString()))
                                score += priority[word[j].ToString()] * (double)Math.Pow(order.Length + 1, order.Length - j); 
                            else
                                throw new Exception();
                        }
                    }
                    //insert each score with their corresponding string as a key,value pair into a BST. This ensures the strings are sorted based on their score form lowest to greatest, 
                    //when an in-order traveral is performed
                    string_score.insert(score, word); //O(logn)
                }
            }
            return string_score.inOrderTraversal().ToArray();
        }