C#入门及进阶|数组和集合(五):数组的查找和排序

数组的查找和排序

1.查找数组元素

static void Main(string[] args)

{

   // TODO: 查找数组元素

   int[] a= new int[100];

   Console.WriteLine("输入数字");

   string s=Console.ReadLine();

    int x=Int32.Parse(s);

   Console.WriteLine("\n 输入int数组元素 \n");

for(int i=0;i<x;i++)

  {

       string s1=Console.ReadLine();

       a[i]=Int32.Parse(s1);

  }

  Console.WriteLine("搜查元素\n");

  string s3=Console.ReadLine();

  int x2=Int32.Parse(s3);

  //循环部分数组

  for(int i=0;i<x;i++)

  {

    if(a[i]==x2)

    {

       Console.WriteLine("Search successful");

       Console.WriteLine("Element {0} found at location {1}\n",x2,i+1);

         break;

     }

  }

}

2.数组排序

        例如:数组元素的冒泡排序。

/*

第一遍使最轻的记录上升到数组的最顶端,

第二遍使剩下的最小的上升到第二位置,

第二遍扫描时不必再比较最顶端的记录

*/

static void Main(string[] args)

{

     int[] a= new int[100];

     Console.WriteLine("输入int数组里的元素数目");

     string s=Console.ReadLine();

     int x=Int32.Parse(s);

     Console.WriteLine("输入元素");

     for(int j=0;j<x;j++)

     {

          string s1=Console.ReadLine();

            a[j]=Int32.Parse(s1);

     }

    int limit= x-1;

   for(int pass=0;pass<x-1;pass++)

   {

        for(int j=0;j<limit-pass;j++)

        {

         if(a[j]>a[j+1])

         {

              int k=a[j]; //数组元素交换

              a[j]=a[j+1]; //数组元素交换

              a[j+1]=k; //数组元素交换

         }

         }

   }

  Console.WriteLine("Sorted elements of an array are(冒泡排序)");

  for (int j=0;j<x;j++)

  {

      Console.WriteLine(a[j]);

  }

      Console.ReadLine ();

}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值