📜  c# sort for loop - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:02.399000             🧑  作者: Mango

代码示例1
//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);
        }