/*您真的理解冒泡排序吗?还是背下来了呢?冒泡排序真的只有一种方法吗?
 *     有些东西别想太复杂,简简单单的解决不是更好?

 *         虽然方法不一样,思想都是大同小异,希望读者仔细体会......
 * */

using System;

namespace Sort
{
    public  class Sort

  {

   //冒泡排序 一 

    //是不是很不好理解?没关系,看看下一种方法,绝对好理解

   public void BubbleSort(int[] a)
        {

    //定义一个临时变量,为了交换位置,学过C语言的我想应该很熟悉吧?
            int tmp;

            for (int i = 0; i < a.Length - 1; i++)
            {
                int idx = i;
//利用数组中的索引是不是也是一种办法?
                for (int j = idx + 1; j < a.Length; j++)
                    if (a[idx] < a[j]) 

                        idx = j; //其实就是为了找到最大的那个数的索引

      //下面就是交换的过程
                tmp = a[i];
                a[i] = a[idx];
                a[idx] = tmp;
            }

        }

   

   //冒泡排序 二  

   //如果你觉的这个难不倒你,我们可以看看下一种呵呵    

   public void BubbleSort(int[] a)
        {

    //定义一个临时变量,为了交换位置,学过C语言的我想应该很熟悉吧?
            int tmp;

            for (int i = 0; i < a.Length - 1; i++)
            {
                 //int idx = i; 这句话是不是可以省略掉了?

      // 这样是不是就更容易通俗易懂了?
                for (int j = i+1; j < a.Length; j++)
                {

       //你比我大我就和你交换,比我小继续找比我大的,如果找不到,我就是最大的对吧?
                    if (a[i] < a[j])
                    {
                        tmp = a[j];
                        a[j] = a[i]; 
                        a[i] = tmp;
                    }
                }
           

          }

   }

 

   //递归算法,模拟冒泡 三

   //稍微有点绕,如果你搞懂前两种再来看会比较简单一点 

   public void BubbleSort(int[] a)
        {

    //调用下面的方法
            bubble(a, 0, a.Length);
        }

        void bubble(int[] a, int start, int end)
        {

    //注意:如果没有这个判断条件就无限递归了
            if (start >= end)
            {
                return;
            }
            int tmp;

    //和上面的两种方法大同小异

            for (int i = start; i < end-1; i++)
            {
                if (a[start] < a[i + 1])
                {
                    tmp = a[start];
                    a[start] = a[i + 1];
                    a[i + 1] = tmp;
                }
            }

    //传说中的递归

            bubble(a, start+1, end);
        }

 }

}

posted on 2010-05-08 01:45  ∞Code∞  阅读(3414)  评论(10编辑  收藏  举报