当前位置:   article > 正文

C语言有趣代码_c语言有趣代码大全

c语言有趣代码大全
  1. 1000内素数
  2. Int main(){
  3.  int a[1001] = {0};
  4.  for(int I = 2;i<=1000;i++){
  5.  if(a[i] == 0){
  6.  printf("%d\n"ni);
  7.  for(int j = i+I; j<=1000; j = j+i){
  8.  a[j] = 1;
  9. }}}
  10. Return 0;
  11. }
  12. 二分法找峰值
  13. #include<stdio.h>
  14. int feng(int* nums, int n) {
  15. int left = 0;
  16. int right = n - 1;
  17. int mid;
  18. while (left < right) {
  19. mid = (left + right) / 2;
  20. if (nums[mid] >= nums[mid + 1]) {
  21. right = mid;
  22. }
  23. else {
  24. left = mid + 1;
  25. }
  26. }
  27. return left;
  28. }
  29. int main(){
  30. int nums[7] = { 0 };
  31. int n = sizeof(nums) / sizeof(int);
  32. for (int i = 0; i < n ; i++) {
  33. scanf("%d", &nums[i]);
  34. }
  35. int a;
  36. a = feng(nums,n);
  37. printf("%d",a );
  38. return 0;
  39. }
  40. 二分法找旋转数组最小值
  41. #include<stdio.h>
  42. int feng(int* nums, int n) {
  43. int left = 0;
  44. int right = n - 1;
  45. int mid;
  46. while (left < right) {
  47. mid = (left + right) / 2;
  48. if (nums[mid] > nums[right]) {
  49. left = mid + 1;
  50. }
  51. else if(nums[mid] < nums[right]){
  52. right = mid;
  53. }
  54. else {
  55. right--;
  56. }
  57. }
  58. return nums[left];
  59. }
  60. int main(){
  61. int nums[5] = { 0 };
  62. int n = sizeof(nums) / sizeof(int);
  63. for (int i = 0; i < n ; i++) {
  64. scanf("%d", &nums[i]);
  65. }
  66. int a;
  67. a = feng(nums,n);
  68. printf("%d",a );
  69. return 0;
  70. }
  71. 摩尔投票
  72. int moertoupiao(int* nums,int n) {
  73. int key = nums[0];
  74. int count = 0;
  75. for (int i = 0; i < n; i++) {
  76. if (nums[i] == key) {
  77. count++;
  78. }
  79. else {
  80. count--;
  81. }
  82. if (count <= 0) {
  83. key = nums[i + 1];
  84. }
  85. }
  86. return key;
  87. }
  88. 三色旗问题
  89. #include<stdio.h>
  90. void exchange(int* a, int* b) {
  91. int c = *a;
  92. *a = *b;
  93. *b = c;
  94. }
  95. void paixu(int* arr,int a,int b) {
  96. int index = 0;
  97. int i = a - 1;
  98. int j = b + 1;
  99. int temp = 1;
  100. while (index<j) {
  101. if (arr[index]==temp) {
  102. index++;
  103. }
  104. else if(arr[index]<temp){
  105. exchange(&arr[++i],&arr[index]);
  106. index++;
  107. }
  108. else if (arr[index]>temp) {
  109. exchange(&arr[--j],&arr[index]);
  110. }
  111. }
  112. }
  113. int main() {
  114. int arr[] = { 1,2,0,2,2,2,1,1,1,0,0,1,2,0,1,2,0,2,1,0,2,1,2,1 };
  115. int n = sizeof(arr) / sizeof(int);
  116. int i = 0;
  117.     paixu(arr,i, n-1);
  118. for (int i = 0; i < n; i++) {
  119. printf("%d ", arr[i]);
  120. }
  121. return 0;
  122. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/486945
推荐阅读
相关标签
  

闽ICP备14008679号