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

举报
陈言必行 发表于 2021/08/13 22:44:06 2021/08/13
【摘要】 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...

   
  1. namespace keshanglianxi6.28_2
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. Random ra= new Random();
  8. int[] arr= new int[10];
  9. for (int i= 0; i < 10; i++)
  10. {
  11. arr[i] = ra.Next(100,999);
  12. }
  13. for (int i= 0; i < arr.Length; i++)
  14. {
  15. Console.Write(arr[i] + "");
  16. }
  17. Console.WriteLine();
  18. sort1(arr);
  19. for (int i= 0; i < arr.Length; i++)
  20. {
  21. Console.Write(arr[i] + "");
  22. }
  23. //int[]arr = { 1, 22, 45, 65, 75, 84, 95, 100, 124 };
  24. Console.WriteLine();
  25. int a =f(arr,222);
  26. if (a ==-1)
  27. {
  28. Console.Write("没有您要查找的数:");
  29. }
  30. else
  31. {
  32. Console.Write("您要查找的数是在第"+(a+1)+"位");
  33. }
  34. Console.ReadLine();
  35. }
  36. //查找,,,
  37. static int f(int[] a, int n)
  38. {
  39. int low,mid, high;
  40. low =0;
  41. high =a.Length - 1;
  42. while (low<= high)
  43. {
  44. mid = (low + high) / 2;
  45. int midVal = a[mid];
  46. if (midVal < n)
  47. {
  48. low = mid + 1;
  49. }
  50. else if (midVal > n)
  51. {
  52. high = mid - 1;
  53. }
  54. else
  55. {
  56. return mid;
  57. }
  58. }
  59. return-1;
  60. }
  61. //排序,,,
  62. static void sort(int []a)
  63. {
  64. int i,j,temp;
  65. for (i =0; i < a.Length; i++) {
  66. for (j = 0; j < a.Length -i-1; j++) {
  67. if (a[j] > a[j + 1])
  68. {
  69. temp =a[j];
  70. a[j] = a[j+ 1];
  71. a[j + 1] =temp;
  72. }
  73. }
  74. }
  75. }
  76. static void sort1(int []a)
  77. {
  78. int i, j,temp;
  79. for (i =1; i < a.Length; i++) {
  80. j = i - 1;
  81. temp = a[i];
  82. while (j >= 0 &&temp < a[j])
  83. {
  84. a[j + 1] = a[j];
  85. j--;
  86. }
  87. a[j + 1] = temp;
  88. }
  89. }
  90. static void sort2(int[]arr)
  91. {
  92. for (int x= 0; x < arr.Length - 1; x++)
  93. {
  94. for (int y = x + 1; y <arr.Length; y++)
  95. {
  96. if (arr[x] > arr[y])
  97. {
  98. int temp =arr[x];
  99. arr[x] =arr[y];
  100. arr[y] =temp;
  101. }
  102. }
  103. }
  104. }
  105. }
  106. }


文章来源: czhenya.blog.csdn.net,作者:陈言必行,版权归原作者所有,如需转载,请联系作者。

原文链接:czhenya.blog.csdn.net/article/details/76091898

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。