zoukankan      html  css  js  c++  java
  • C#冒泡排序

    最早写冒泡排序是在上学的时候,用c语言实现的,工作后再也没写过这个无用的算法,然后见网上很多人执着于这个算法,甚至用他来评价一个程序员的素质,于是乎试着用C#写了一遍。

    程序中的后三行注释用于避免对已排序好的数组进行重复排序

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

    namespace BubbleSortCSharp
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] arr = { 1838279,9,95111103020 };

                BubbleSort bubbleSort = new BubbleSort();
                bubbleSort.BubbleSortCSharp(arr);
                //bubbleSort.BubbleSortCSharp(arr); //比较对有序数组和无序数组排序时的执行情况
                for (int i = 0; i < arr.Length; i++)
                {
                    System.Console.WriteLine(arr[i].ToString());
                }

                System.Console.Read();
            }

            class BubbleSort
            {
                public void BubbleSortCSharp(int[] arr)
                {
                    for (int i = 0; i < arr.Length; i++)
                    {
                        //bool flag = true;
                        for (int j = 0; j < arr.Length - i - 1; j++)
                        {
                            if (arr[j] > arr[j + 1])
                            {
                                Swap(ref arr[j], ref arr[j + 1]);
                                //flag = false;
                            }
                        }
                        //if (flag) break;
                    }
                }

                protected void Swap(ref int x, ref int y)
                {
                    x = x + y;
                    y = x - y;
                    x = x - y;
                }

            }
        } }


  • 相关阅读:
    函数
    拉取代码到本地
    逻辑位运算符 以及 布尔运算符&&、||
    JS中substr与substring的区别
    ? :和!:的用法含义及es6语法...
    JS中attribute和property的区别
    并发、并行的理解
    斑鸠云商小程序记住账号和密码
    js中的foreach用法
    指针与数组
  • 原文地址:https://www.cnblogs.com/zyip/p/2396063.html
Copyright © 2011-2022 走看看