Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

c# sort for loop

//Bubble Sort

-----------------------------------------------option 1 (int Desc) 
public static void Main(string[] args)
        {
            int[] arr = { 5, 4, 8, 11, 1 };
            Sorting(arr);
        }
        public static void Sorting(int[] arr)
        {
            int length = arr.Length;

            for (int i = 0; i < length - 1; i++)
            {   //length-1 b/c i+1 will put you OOB

                if (arr[i] < arr[i + 1])
                {//For descending order...skips to next index if false

                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;

                    i = -1; //sort from lowest out of order index
                }
            }
            foreach (int item in arr)
            {
                Console.WriteLine(item);
            }
        }
--------------------------------------------------Option 2 (string Asc)

static void Main(string[] args)
        {
            Sorting("zxeba");
        }

        public static void Sorting(string s)
        {
            var arr = s.ToArray();

            for (int i = 0; i < arr.Length; i++)
            {
                for (int j = 0; j < arr.Length - 1; j++)
                {
                    if (arr[j+1] < arr[j])
                    {
                        char temp = arr[j+1]; //Hold smaller
                        arr[j+1] = arr[j]; //big val to index on R
                        arr[j] = temp; // small val to index on L
                    }
                }
            }   
            string result = String.Join("", arr);

            Console.WriteLine(result);
        }
Comment

PREVIOUS NEXT
Code Example
Csharp :: get all components of type unity 
Csharp :: C# datareadeer return null 
Csharp :: c# add button to messagebox 
Csharp :: get percentage c# 
Csharp :: copy class c# 
Csharp :: mvc write to console 
Csharp :: trim c# 
Csharp :: rotation unity script 2d 
Csharp :: checking if a list contains a value unity 
Csharp :: increase value in dictionary against a key in c# 
Csharp :: c# remove all whitespaces from string 
Csharp :: how to chceck for a tag in a trigger enter 2d unity 
Csharp :: vb.net add row to datagridview programmatically 
Csharp :: c# convert long to int 
Csharp :: how to read a text file C# 
Csharp :: Show private fields in Unity Inspector 
Csharp :: input unity 
Csharp :: array reduce c# 
Csharp :: c# convert to nullable datetime 
Csharp :: c# wpf timer 
Csharp :: make 2D object move at constant speed unity 
Csharp :: entity framework core db first 
Csharp :: unity reset random seed 
Csharp :: how set cascade on delete and update in same time in laravel 
Csharp :: on trigger unity 
Csharp :: iterate though data in firebase unity 
Csharp :: c# winscp upload file 
Csharp :: microsoft forms create bitmap 
Csharp :: ??= mean C# 
Csharp :: c# add strings 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =