[C#]冒泡排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/david_520042/article/details/51930731

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

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();
        }

    }
}

这里写图片描述

展开阅读全文

没有更多推荐了,返回首页