zoukankan      html  css  js  c++  java
  • 冒泡排序 二分法查找

    一、冒泡排序
    趟数和次数:
    每趟出来一个最小(最大)的数。
    每次比较相邻的两个数,按要求交换位置。

     int[] a = new int[8] { 9, 21, 8, 13, 16, 22, 7, 6 };
                Console.WriteLine("************排序之前*************");
                for (int i = 0; i < a.Length; i++)
                {
                    Console.Write(a[i] + "	");
                }
                Console.WriteLine();
                //排序
                for (int i = 1; i<=a.Length-1; i++)   //趟数  n-1
                {
                    for (int j = 1;j<=a.Length-i ; j++)  //每趟中比较的次数  n-i
                    {
                        if (a[j - 1] > a[j])
                        {
                            int temp = a[j - 1];
                            a[j - 1] = a[j];
                            a[j] = temp;
                        }
                    }
                }
                Console.WriteLine();
                Console.WriteLine("************排序之后*************");
                for (int i = 0; i < a.Length; i++)
                {
                    Console.Write(a[i] + "	");
                }
                Console.WriteLine();

    二、二分查询
    前提:数组必须是有序的。

                int[] a = new int[] { 22, 21, 16, 13, 9, 8, 7, 6 };
    
                //从键盘接收要查找的数。
                int find = Convert.ToInt32(Console.ReadLine());
    
                int maxsub, minsub, midsub;
                minsub = 0;
                maxsub = a.Length - 1;
    
                for (;maxsub >= minsub ; )
                {
                    midsub = (maxsub + minsub) / 2; //求中间下标
                    if (a[midsub] == find)  //看看找到了没有?
                    {
                        Console.WriteLine("恭喜找到了,在第" + midsub + "个位置上");
                        break;
                    }
                    else //这次没找到
                    {
                        if (a[midsub] > find)   //扔掉上半
                        {
                            minsub = midsub + 1; 
                        }
                        else    //扔掉下半
                        {
                            maxsub = midsub - 1;
                        }
                    }
                }
  • 相关阅读:
    CF733F
    P4826
    洛谷P2687 & P1108
    CF42A
    洛谷P1858
    CF1428C
    洛谷P4981
    树形DP
    背包六讲(也不知道为啥就是六个 $QwQ$)
    2020
  • 原文地址:https://www.cnblogs.com/languang/p/4535308.html
Copyright © 2011-2022 走看看