现在的位置: 首页 > 综合 > 正文

冒泡排序(包括升序和降序)

2013年09月17日 ⁄ 综合 ⁄ 共 1424字 ⁄ 字号 评论关闭

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SortDataDemo
{
    public partial class SortData : Form
    {
        public SortData()
        {
            InitializeComponent();
        }

        private void btnAsc_Click(object sender, EventArgs e)
        {
            Sort(true);
        }
        public void Sort(bool isAsc)
        {
            lboData.Items.Clear();
            int[] arr = new int[] { 1, 4, 3, 5, 8, 8 };
            int temp;
            int length = arr.Length;
            for (int i = 0; i < length; i++)
            {
                for (int j = i + 1; j < length; j++)
                {
                    //升序排列
                    if (isAsc)
                    {
                        if (arr[i] > arr[j])
                        {
                            temp = arr[i];
                            arr[i] = arr[j];
                            arr[j] = temp;
                        }
                    }
                    else
                    {
                        if (arr[i] < arr[j])
                        {
                            temp = arr[i];
                            arr[i] = arr[j];
                            arr[j] = temp;
                        }
                    }
                }
                lboData.Items.Add(arr[i]);
            }
        }

        private void btnDesc_Click(object sender, EventArgs e)
        {
            Sort(false);
        }
    }
}

 

上面代码升序输出结果为:

 

【上篇】
【下篇】

抱歉!评论已关闭.