C# - 排序与快速排序多个字符串数组 [英] c# - Sorting Multiple String arrays with Quicksort

查看:180
本文介绍了C# - 排序与快速排序多个字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉的模糊标题,但我会努力和最好的,我可以在下面描述一下我的问题。

Sorry for the vague title but I'll try and describe what my problem as best as I can below.

基本上我有5个字符串数组,所有持有相关于其他阵列相同的索引数据。例如,元件5在阵列1对应于元件5在阵列2,3,4和5

Basically I have 5 string arrays that all hold data relevant to the same index in the other arrays. For example, element 5 in array 1 corresponds to element 5 in arrays 2, 3, 4 and 5.

我所做的是用来快速排序algorthim排序阵列1成字母顺序排列。的问题是,当该数组排序,不再做在其他阵列元素对应由于其它阵列没有被排序。

What I have done is used the Quicksort algorthim to sort array 1 into alphabetical order. The problem is that when the array is sorted, no longer do elements in the other arrays correspond since the other arrays haven't been sorted.

我需要的是一些方法来在其他4个阵列周围交换元件相同的元件一直下降到阵列1例如,如果元件2在阵列1被交换到元件55,则元件2中的其它4个阵列需要在其阵列,反之亦然被换到55元。

What I need is some way to swap the same elements around in the other 4 arrays as has been down to array 1. For example, if element 2 in array 1 is swapped to element 55, then element 2 in the other 4 arrays need to be swapped to element 55 in their array and vice versa.

的最终目标是在所有5阵列显示特定元素的所有数据。

The end goal is to display all the data in a specific element across all 5 arrays.

下面我加我使用的是快速排序算法,并补充说,需要整理3为例数组:

Below I have added the quicksort algorithm I'm using and added 3 example arrays that need sorting:

   string[] array1 = {"z","y","x","a"};
   string[] array2 = {"26","25","24","1"}; 
   string[] array3 = { "black","yellow","white","red" };


   // The first 2 arrays should clarify my point further. 

  // I use Quicksort to sort array 1 


   public static void QuicksortSTRING(IComparable[] elements, int left, int right)  
   {        
         int i = left, j = right;  
         IComparable pivot = elements[(left + right) / 2];  

         while (i <= j)  
         {  
            while (elements[i].CompareTo(pivot) < 0)  
            {  
              i++;  
            }

            while (elements[j].CompareTo(pivot) > 0)
            {
              j--;
            }

            if (i <= j)
            {
                // Swap
                IComparable tmp = elements[i];
                elements[i] = elements[j];
                elements[j] = tmp;

                i++;
                j--; 
            }
        }

        // Recursive calls

        if (left < j)
        {
           QuicksortSTRING(elements, left, j);
        }

        if (i < right)
        {     
           QuicksortSTRING(elements, i, right); 
        }
    } 

如果您需要任何其他信息就问。

If you need any other info just ask.

推荐答案

这是更好地把三个相关的字符串成一个对象:

It’s better to put the three related strings into a single object:

sealed class RelatedInformation     // or struct, you decide
{
    public string First;
    public string Second;
    public string Third;
}

和再排序这些对象的列表:

and then sort a list of those objects:

var myList = new List<RelatedInformation>();
// insert code that populates the list here
myList.Sort((a, b) => a.First.CompareTo(b.First));

,或者,如果它需要一个数组:

or, if it needs to be an array:

var myArray = /* obtain the RelatedInformation[] here */;
Array.Sort(myList, (a, b) => a.First.CompareTo(b.First));

此外,没有必要为你实现自己的快速排序(除非这是作业?:))。你可以使用的Array.Sort 名单&LT; T&GT;的.sort 用一个lambda前pression指定你的排序标准。

Additionally, there is no need for you to implement Quicksort yourself (unless this is homework? :)). You can just use Array.Sort or List<T>.Sort with a lambda expression that specifies your sort criterion.

您甚至不需要实施 IComparable的&LT; T&GT。但是,如果 RelatedInformation 类(或结构),在有一些与他们的排序很多地方被使用,它可能是明智反正来实现它;那么你可以沟lambda表达式:

You don’t even need to implement the IComparable<T> interface if you use the above code. However, if the RelatedInformation class (or struct) is used in many places that have something to do with their ordering, it may be wise to implement it anyway; then you can ditch the lambdas:

sealed class RelatedInformation : IComparable<RelatedInformation>
{
    public string First;
    public string Second;
    public string Third;

    public int CompareTo(RelatedInformation other)
    {
        return First.CompareTo(other.First);
    }
}

// ...

var myList = new List<RelatedInformation>();
// insert code that populates the list
myList.Sort();


不过,既然你明确地询问三阵的局面,这里是将这个约束下工作的解决方案。代替排序阵列中的任一项的,这个想法是要排序的的索引的列表的。我将使用LINQ这个,因为它是pretty succint和可读性:


However, since you explicitly asked about the three-array situation, here is a solution that will work under that constraint. Instead of sorting any one of the arrays, the idea is to sort a list of the indexes. I’m going to use LINQ for this because it’s pretty succint and readable:

var sortedIndexes = Enumerable.Range(0, array1.Length)
                        .OrderBy(i => array1[i])
                        .ToArray();

var sortedArray1 = sortedIndexes.Select(i => array1[i]).ToArray();
var sortedArray2 = sortedIndexes.Select(i => array2[i]).ToArray();
var sortedArray3 = sortedIndexes.Select(i => array3[i]).ToArray();

pretty短,是吧?当然,在调用排序依据,您可以指定任何其他数组排序。

Pretty short, huh? Of course, in the call to OrderBy, you can specify any other array to sort by.

请注意,虽然这code将抛出一个异常,如果任何的数组是的缩短的比第一个,它会悄悄地丢弃的物品,如果任何阵列是的比第一个。列表的对象,该解决方案的一个主要好处是,你不必担心。

Do be aware though that this code will throw an exception if any of the arrays is shorter than the first one, and it will silently discard items if any of the arrays is longer than the first one. One major benefit of the list-of-objects solution is that you do not need to worry about that.

作为一个额外的资料片,在排序依据从LINQ是的稳定的排序的;这意味着项目,其中数组1 具有相同的字符串留在同一顺序。 的Array.Sort 列表&LT; T&GT;的.sort 没有一个稳定的排序

As an added piece of information, the OrderBy from LINQ is a stable sort; this means that items where array1 has the same string stay in the same order. Array.Sort and List<T>.Sort do not have a stable sort.

您甚至可以使用该方法,通过多个条件进行排序;例如,假设你想在数组1 的字符串进行排序的,但每当数组1 有一些相同的字符串项目,你想这些项目通过无论是在数组2 进行排序。你可以这样做,使用 ThenBy

You can even use this method to sort by multiple criteria; for example, let’s say you want to sort by the strings in array1, but whenever array1 has the same string for some items, you want those items to be sorted by whatever is in array2. You can do that using ThenBy:

var sortedIndexes = Enumerable.Range(0, array1.Length)
                        .OrderBy(i => array1[i])
                        .ThenBy(i => array2[i])
                        .ToArray();

这篇关于C# - 排序与快速排序多个字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆