Qual è il modo più elegante di ordinamento della shell (ordinamento a pettine/incremento decrescente) in C#?

StackOverflow https://stackoverflow.com/questions/1596346

Domanda

Esiste un modo migliore per eseguire l'ordinamento della shell utilizzando C#?

// array of integers to hold values
private int[] a = new int[100];

// number of elements in array
private int count;

// Shell Sort Algorithm
public void sortArray()
{
  int i, j, increment, temp;

  increment = 3;

  while( increment > 0 )
  {
    for( i=0; i < count; i++ )
    {
      j = i;
      temp = a[i];

      while( (j >= increment) && (a[j-increment] > temp) )
      {
        a[j] = a[j - increment];
        j = j - increment;
      }

      a[j] = temp;
    }

    if( increment/2 != 0 )
    {
      increment = increment/2;
    }
    else if( increment == 1 )
    {
      increment = 0;
    }
    else
    {
      increment = 1;
    }
  }
}

A proposito, me lo chiedo perché ho alcuni esempi diversi di ordinamenti 'eleganti' in diverse lingue (come il bubble sorting in C# E F#), e li sto confrontando.Nella vita reale, probabilmente utilizzerei quanto segue per la maggior parte del tempo in C#:

Array.Sort( object[] )

Non mi interessa se questi sono modelli “accademici” e non pragmatici.Puoi down-modificarmi nell'oblio se vuoi :)

KA

È stato utile?

Soluzione

I miglioramenti si potrebbe facilmente fare:

  • Non tenere lo stato nell'oggetto. Questo dovrebbe essere facile da fare solo con le variabili locali.
  • Uso convenzionale C # nomi come ShellSort piuttosto che shellSort
  • Utilizzare nomi significativi come count invece di x
  • Utilizzare l'operatore condizionale, per es.

    // This replaces your last 12 lines
    int halfIncrement = increment / 2;
    increment = halfIncrement != 0 ? halfIncrement : 1 - increment;
    
  • Fare il codice generico - perché limitarvi a interi

  • Crea il tuo metodo di prendere i dati in questione, e ne fanno un IList<T>
  • Fare l'ordinamento arbitrario tramite un IComparer<T>, fornendo un sovraccarico che utilizza il valore predefinito.
  • Dichiarazione delle variabili più tardi possibile per ridurre il loro campo di applicazione e migliorare la leggibilità

Molto poco di questo è in realtà sorta legati - non ho verificato se il codice è in realtà un legittimo shell sort o no ...

Altri suggerimenti

Nel mio test questo è dal 75% al ​​90% più veloce dell'ordinamento di array con lo stesso comparatore System.Func.Lo uso per ordinare una struttura personalizzata.puoi facilmente modificarlo per ordinare le classi.

public class DualQuickSort<T> where T : struct
    {
        private readonly System.Func<T, T, int> comparer;
        public DualQuickSort(System.Func<T, T, int> comparer)
        {
            this.comparer = comparer;
        }

    public DualQuickSort(IComparer<T> comparer)
        : this(comparer.Compare)
    {

    }

    public  void Sort(T[] a)
    {
        Sort(a, 0, a.Length);
    }
    public  void Sort(T[] a, int fromIndex, int toIndex)
    {
        RangeCheck(a.Length, fromIndex, toIndex);

        DualPivotQuicksort(a, fromIndex, toIndex - 1, 3);
    }
    private static void RangeCheck(int length, int fromIndex, int toIndex)
    {
        if (fromIndex > toIndex)
        {
            throw new ArgumentException("fromIndex > toIndex");
        }
        if (fromIndex < 0)
        {
            throw new IndexOutOfRangeException(fromIndex + " is less than 0");
        }
        if (toIndex > length)
        {
            throw new IndexOutOfRangeException(toIndex + " is greater than " + fromIndex);
        }
    }

    private static void Swap(T[] a, int i, int j)
    {
        var temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    private  void DualPivotQuicksort(T[] a, int left, int right, int div)
    {
        var len = right - left;

        if (len < 27)
        { // insertion sort for tiny array
            for (var i = left + 1; i <= right; i++)
            {
                for (var j = i; j > left && comparer(a[j] , a[j - 1])==-1; j--)

                {
                    Swap(a, j, j - 1);
                }
            }
            return;
        }
        var third = len / div;
        // "medians"
        var m1 = left + third;
        var m2 = right - third;
        if (m1 <= left)
        {
            m1 = left + 1;
        }
        if (m2 >= right)
        {
            m2 = right - 1;
        }
        if (comparer(a[m1] , a[m2])==-1)
        {
            Swap(a, m1, left);
            Swap(a, m2, right);
        }
        else
        {
            Swap(a, m1, right);
            Swap(a, m2, left);
        }
        // pivots
        var pivot1 = a[left];
        var pivot2 = a[right];
        // pointers
        var less = left + 1;
        var great = right - 1;
        // sorting
        for (var k = less; k <= great; k++)
        {
            if (comparer(a[k] , pivot1)==-1)
            {
                Swap(a, k, less++);
            }
            else if (comparer(a[k], pivot2) == 1)
            {
                while (k < great && comparer(a[great] , pivot2)==1)
                {
                    great--;
                }
                Swap(a, k, great--);
                if (comparer(a[k], pivot1) == -1)
                {
                    Swap(a, k, less++);
                }
            }
        }
        // Swaps
        var dist = great - less;
        if (dist < 13)
        {
            div++;
        }
        Swap(a, less - 1, left);
        Swap(a, great + 1, right);
        // subarrays
        DualPivotQuicksort(a, left, less - 2, div);
        DualPivotQuicksort(a, great + 2, right, div);

        // equal elements
        if (dist > len - 13 && comparer(pivot1,pivot2)!=0)
        {
            for (int k = less; k <= great; k++)
            {
                if (comparer(a[k] , pivot1)==0)
                {
                    Swap(a, k, less++);
                }
                else if (comparer(a[k], pivot2) == 0)
                {
                    Swap(a, k, great--);
                    if (comparer(a[k], pivot1) == 0)
                    {
                        Swap(a, k, less++);
                    }
                }
            }
        }
        // subarray
        if (comparer(pivot1 , pivot2)==-1)
        {
            DualPivotQuicksort(a, less, great, div);
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top