How to remove Duplicate Value from an Unsorted Array



 Remove Duplicate Value from an Unsorted Array


How to remove Duplicate Value from an Array

Array
7
8
6
1
1
3
2
2
7
6
3
8
7


Above is Unsorted Array
Output Should be
1
2
3
6
7
8









Solution

Step 1: You have Unsorted Array, Now sort the Array
Step 2: You can use Array.Sort(Name of Array ) method to sort the array / or simply by code

1
1
2
2
3
3
6
6
7
7
7
8
8

Step 3 : Take a Temp Array to store the distinct value in array
The logic behind the find distinct value is
Check pointed value to next value  i.e Array1[1] = 7and Array1[1]= 1and

If both value not equal, then store in new array
1
2
3
6
7
8









            int[] array1 = { 7,8,6,1,1,3,2,2,7,6,3,8,7 };
            Array.Sort(array1);
            array1.Reverse();
            int[] NewArr = new int[array1.Length];
            int n,j = 0;
            for (int i = 0; i <= array1.Length - 2; i++)
            {
                if (array1[i] != array1[i + 1])
                {
                    NewArr[j] = array1[i];
                    j++;
                }
            }
            NewArr[j] = array1[array1.Length - 1];

            for (n = 0; n <= j; n++)
            {
                Console.WriteLine("New array " + NewArr[n]);
            }
           
                   
            Console.ReadLine();



Share:

No comments:

Post a Comment

Popular

Tags

Mobile

Recent Posts