当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++基础入门教程

十行代码搞定 冒泡排序

    Java Code:
    class Class1
    {
     static void bubbleSort(int[] a)
     {
      for (int j = a.length - 1; j > 0; j--) // outer loop (backward)
       for (int i = 0; i < j; i++) // inner loop (forward)
        if (a[i] > a[i+1]) //Swap
        {
         a[i] = a[i] + a[i+1];
         a[i+1] = a[i] - a[i+1];
         a[i] = a[i] - a[i+1];
        }
     }
     public static void main(String[] args)
     {
      int[] a = new int[];
      //int[] a = new int[];
      bubbleSort(a);
      for (int i=0; i < a.length; i++)
      {
       System.out.println(a[i]);
      }
     }
    }

    C# Code:
    class Class1
    {
     static void BubbleSort(int[] a)
     {
      for (int j = a.Length - 1; j > 0; j--) // outer loop (backward)
       for (int i = 0; i < j; i++) // inner loop (forward)
        if (a[i] > a[i+1])
        {
         //a[i] = a[i] + a[i+1];
         //a[i+1] = a[i] - a[i+1];
         //a[i] = a[i] - a[i+1];
         Swap(ref a[i],ref a[i+1]);
        }
     }
     static void Swap(ref int x,ref int y)
     {
      x = x + y;
      y = x - y;
      x = x - y;
     }
     static void Main(string[] args)
     {
      int[] a = new int[];
      //int[] a = new int[];
      BubbleSort(a);
      for (int i=0; i < a.Length; i++)
      {
       System.Console.WriteLine(a[i]);
      }
      System.Console.ReadLine();
     }
    }

    http://dev.csdn.net/user/playyuer

相关内容
赞助商链接