数组(随机生成,三种排序,二分查找)

来源:互联网 发布:网络用语鱼是什么意思 编辑:程序博客网 时间:2024/05/16 11:53
namespace keshanglianxi6.28_2{    class Program    {       static void Main(string[] args)       {           Random ra= new Random();           int[] arr= new int[10];           for (int i= 0; i < 10; i++)           {              arr[i] = ra.Next(100,999);           }           for (int i= 0; i < arr.Length; i++)           {              Console.Write(arr[i] + "");           }          Console.WriteLine();          sort1(arr);           for (int i= 0; i < arr.Length; i++)           {              Console.Write(arr[i] + "");           }           //int[]arr = { 1, 22, 45, 65, 75, 84, 95, 100, 124 };          Console.WriteLine();           int a =f(arr,222);           if (a ==-1)           {             Console.Write("没有您要查找的数:");           }           else           {             Console.Write("您要查找的数是在第"+(a+1)+"位");           }          Console.ReadLine();       }       //查找,,,       static int f(int[] a, int n)       {           int low,mid, high;           low =0;           high =a.Length - 1;           while (low<= high)           {              mid = (low + high) / 2;              int midVal = a[mid];              if (midVal < n)              {                 low = mid + 1;              }              else if (midVal > n)              {                 high = mid - 1;              }              else              {                 return mid;              }           }           return-1;       }       //排序,,,       static void sort(int []a)       {           int i,j,temp;           for (i =0; i < a.Length; i++) {              for (j = 0; j < a.Length -i-1; j++) {                 if (a[j] > a[j + 1])                 {                     temp =a[j];                     a[j] = a[j+ 1];                     a[j + 1] =temp;                 }              }           }       }       static void sort1(int []a)       {           int i, j,temp;           for (i =1; i < a.Length; i++) {              j = i - 1;              temp = a[i];              while (j >= 0 &&temp < a[j])              {                 a[j + 1] = a[j];                 j--;              }              a[j + 1] = temp;           }       }  static void  sort2(int[]arr)       {           for (int x= 0; x < arr.Length - 1; x++)            {              for (int y = x + 1; y <arr.Length; y++)              {                 if (arr[x] > arr[y])                 {                     int temp =arr[x];                     arr[x] =arr[y];                     arr[y] =temp;                 }              }           }       }    }}


阅读全文
1 0
原创粉丝点击