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

            }
        } }


  • 相关阅读:
    hdu 3342 Legal or Not 拓排序
    hdu 1596 find the safest road Dijkstra
    hdu 1874 畅通工程续 Dijkstra
    poj 2676 sudoku dfs
    poj 2251 BFS
    poj Prime Path BFS
    poj 3278 BFS
    poj 2387 Dijkstra 模板
    poj 3083 DFS 和BFS
    poj 1062 昂贵的聘礼 dijkstra
  • 原文地址:https://www.cnblogs.com/zyip/p/2396063.html
Copyright © 2011-2022 走看看