What's the most elegant way to bubble-sort in C#?

后端 未结 10 1860
旧巷少年郎
旧巷少年郎 2020-12-06 03:33

Can this be cleaned up?

using System;  
class AscendingBubbleSort 
{     
    public static void Main()
    {
        int i = 0,j = 0,t = 0;
        int []c=         


        
10条回答
  •  自闭症患者
    2020-12-06 03:50

    int[] array = {4,5,7,1,8};           
    
    int n1, n2;
    bool stillgoing = true;
    
    while (stillgoing)
    {
        stillgoing = false;
        for (int i = 0; i < (array.Length-1); i++)
        {                  
            if (array[i] > array[i + 1])
            {
                n1 = array[i + 1];
                n2 = array[i];
    
                array[i] = n1;
                array[i + 1] = n2;
                stillgoing = true; 
            }
        }
    }
    for (int i = 0; i < array.Length; i++)
    {
        Console.WriteLine(array[i]);
    }
    

    Took some ideas from Jon skeet...

提交回复
热议问题