2015-05-23 20 views
0

我有一個字節數組,例如byte[] = new byte[3] { 97, 98, 99, 99, 96 }在真實情況下字節數組要長得多。C#字節數組排序它的旋轉

我怎樣才能得到這個數組的所有旋轉和排序呢?而且我還需要將原始索引保存在排序列表中。

輪作應該是這樣的:

{ 97, 98, 99, 99, 96 }, 
{ 98, 99, 99, 96, 97 }, 
{ 99, 99, 96, 97, 98 }, 
{ 99, 96, 97, 98, 99 }, 
{ 96, 97, 98, 99, 99 } 

然後,我需要對它進行排序得到:

{ 96, 97, 98, 99, 99 }, 
{ 97, 98, 99, 99, 96 }, // <- index in rotated list/array 
{ 98, 99, 99, 96, 97 }, 
{ 99, 96, 97, 98, 99 }, 
{ 99, 99, 96, 97, 98 } 

我使用效率不高的方式轉換成字節[]到字符串,然後創建數組字符串,每個數組元素保持它的旋轉,並在那之後對字符串進行排序。我還使用內置函數「排序」,所以我無法抓住我的索引。也許有可能使用LINQ或類似的東西來做到這一點?

回答

1

您可以擴展數組並在那裏進行排序。您將需要創建自己的排序機制:

public static int[] SortAndReturnIndexes(this byte[]) 
{ 
    var indexArray = new int[]; 
    // Your sort logic goes here 
    return indexArray; 
} 
0

取決於你想用它做什麼你做了這些操作後,身體產生的結果未必是最好的事情。舉個例子以下類:

public class Rotation[T] { 

    private int init; 
    private T[] src; 

    public Rotation(T[] src, init){ 
    this.init = init; 
    this.src = src; 
    } 

    public T this[int i] { //indexer 
    get { 
     int realindex = (i + init) % src.Length; //rotate the index 
     return src[realindex]; 
    } 
    } 
} 

你可以使用它作爲

byte[] src = new byte[5] { 97, 98, 99, 99, 96 } 

//rotate by 2 

Rotation[byte] rotation = new Rotation(src, 2); 

rotation[0] == 99 

對它進行排序,最好創建一個自定義的Icomparable,它可以喂排序方法:https://msdn.microsoft.com/en-us/library/8ehhxeaf%28v=vs.110%29.aspx