[C#]冒泡排序

数组类测试环境与排序算法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Data_structure_and_algorithm
{
    class CArray
    {
        private int[] arr;
        private int upper;
        private int numElements;
        public CArray(int size) 
        {
            arr =new  int[size];
            upper = size - 1;
            numElements = 0;
        }

        public void Insert(int item) 
        {
            arr[numElements] = item;
            numElements++;
        }
        public void DisplayElements() 
        {
            for (int i = 0; i <= upper; i++) 
            {
                Console.Write(arr[i]+" ");
            }
            Console.WriteLine();
        }
        public void Clear() 
        {
            for (int i = 0; i <= upper; i++) 
            {
                arr[i] = 0;
                numElements = 0;
            }
        }
         public void BubbleSort() 
        {
            int temp;
            for (int outer = upper; outer >= 1; outer--) 
            {
                for (int inner = 0; inner <= outer - 1; inner++) 
                {
                    if ((int)arr[inner] > arr[inner + 1]) 
                    {
                        temp = arr[inner];
                        arr[inner] = arr[inner + 1];
                        arr[inner + 1] = temp;
                    }
                }
                this.DisplayElements();
            }
        }
    }
}

校验排序过程与结果

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Data_structure_and_algorithm
{
    class Program
    {
        static void Main(string[] args)
        {
            BubbleSort();
        }
        public static void BubbleSort()
        {
            CArray nums = new CArray(10);
            Random rnd = new Random(100);
            for (int i = 0; i < 10; i++)
            {
                nums.Insert(rnd.Next(0,100));
            }
            Console.WriteLine("Before sorting:");
            nums.DisplayElements();
            Console.WriteLine("During sorting:");
            nums.BubbleSort();
            Console.WriteLine("After sorting:");
            nums.DisplayElements();
            Console.ReadKey();
        }

    }
}

这里写图片描述

©️2020 CSDN 皮肤主题: 鲸 设计师:meimeiellie 返回首页
实付 99.00元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值