c# sort forloop code example

Example: 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);
        }