Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# sort int array

 /// <summary>
        /// Sort Int Array
        /// </summary>
        /// <param name="sortBy">A- Ascendig, D- Descending order</param>
        /// <param name="arr">int array to sort</param>
        /// <returns>Sorted Array </returns>
/// Sorting without using the build sort in C# and using unlimited int array parameters using the params keyword
        public static int [] SortArray(char sortBy, params int [] arr)
        {
            int tmp;
            for(int x =0; x< arr.Length - 1; x++)
            {
                // traverse i + 1 
                for(int j =x + 1; j < arr.Length; j++)
                {
                    //compare and swap
                    if (sortBy.Equals('A'))
                    {
                        if (arr[x] > arr[j])
                        {
                            tmp = arr[x];
                            arr[x] = arr[j];
                            arr[j] = tmp;
                        }
                    }else if(sortBy.Equals('D'))
                    {
                        if (arr[x] < arr[j])
                        {
                            tmp = arr[x];
                            arr[x] = arr[j];
                            arr[j] = tmp;
                        }
                    }else
                    {
                        if (arr[x] > arr[j])
                        {
                            tmp = arr[x];
                            arr[x] = arr[j];
                            arr[j] = tmp;
                        }
                    }
                }
            }
            return arr;
        }
 
PREVIOUS NEXT
Tagged: #sort #int #array
ADD COMMENT
Topic
Name
7+4 =