zoukankan      html  css  js  c++  java
  • 冒泡排序算法举例



       static void Main(string[] args)
            {
               int[]a= Read();//读数据
               Sort(ref a);//排序
               Write(a);//输出数据 
            }

     读数据
     1         /// <summary>
    2 /// 读数据
    3 /// </summary>
    4 /// <returns></returns>
    5 public static int[] Read()
    6 {
    7 int i;
    8
    9 int[] a = new int[5];
    10 for (int j = 0; j < 5; j++)
    11 {
    12 i = Int32.Parse(Console.ReadLine());
    13 a[j] = i;
    14 }
    15 return a;
    16
    17 }
    对数据排序
     1  public static void Sort(ref int[] a)
    2 {
    3 for (int m = 0; m < a.Length; m++)
    4 {
    5 for (int j = m + 1; j < a.Length; j++)
    6 {
    7 if (a[m] > a[j])
    8 {
    9 int temp; temp = a[m];
    10 a[m] = a[j]; a[j] = temp;
    11 }
    12 }
    13 }
    14 }


     

    输出数据
    1 public static void Write(int[] a)
    2 {
    3 for (int k = 0; k < a.Length; k++)
    4 {
    5 Console.WriteLine(a[k]);
    6 }
    7 }

    双向冒泡算法举例:

    View Code
     1 static void Main(string[] args)
    2 {
    3 int i;
    4 int[] r = Read();
    5 int start=0,end=r.Length-1;
    6 while(start<=end)
    7 {
    8 for (i = start; i < r.Length-1; i++)
    9 {
    10 if(r[i]>r[i+1])
    11 {
    12 int temp;
    13 temp = r[i];
    14 r[i] = r[i + 1];
    15 r[i + 1] = temp;
    16 }
    17 }
    18 for (i = end; i > start; i--)
    19 {
    20 if (r[i] < r[i-1])
    21 {
    22 int temp;
    23 temp = r[i];
    24 r[i] = r[i - 1];
    25 r[i - 1] = temp;
    26
    27 }
    28 }
    29 start++;
    30
    31 }
    32 for (int j = 0; j < r.Length; j++)
    33 {
    34 Console.WriteLine(r[j]);
    35 }
    36
    37
    38 }


          

    凡事用心去做,认真对待!
  • 相关阅读:
    BZOJ 1907: 树的路径覆盖
    BZOJ 1295: [SCOI2009]最长距离
    BZOJ 1303: [CQOI2009]中位数图
    BZOJ 1468: Tree
    BZOJ 3784: 树上的路径
    BZOJ 2006: [NOI2010]超级钢琴
    BZOJ 1831: [AHOI2008]逆序对
    BZOJ 2521: [Shoi2010]最小生成树
    HDU 6685 Rikka with Coin (枚举 思维)
    HDU 6659 Acesrc and Good Numbers (数学 思维)
  • 原文地址:https://www.cnblogs.com/lsysunbow/p/2369395.html
Copyright © 2011-2022 走看看