Removes the duplicates in sorted array. - CSharp System

CSharp examples for System:Array Sort

Description

Removes the duplicates in sorted array.

Demo Code


using System.Collections.Generic;
using System;/*from   w w w . j  a  va 2s .c o m*/

public class Main{
    /// <summary>
      /// Removes the duplicates in sorted array.
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="arr">The array.</param>
      /// <param name="equalityFunc">The equality function.</param>
      /// <param name="len">The length.</param>
      public static void RemoveDuplicatesInSortedArray<T>(this T[] arr, Func<T, T, bool> equalityFunc, ref int len) {
         len.CheckIsBetween("len", 0, arr.Length);
         if (len <= 1) return;

         var lastValue = arr[0];
         var erased = 0;
         var i = 1;
         var writeIndex = 1;
         while (i < len) {
            if (!equalityFunc(arr[i], lastValue)) {
               lastValue = arr[i];
               if (writeIndex != i) {
                  arr[writeIndex] = arr[i];
               }
               writeIndex++;
            }
            i++;
         }
         len = writeIndex;
      }
}

Related Tutorials