• 冒泡、二分排序


     1 #include<stdio.h>
     2 
     3 void main()
     4 {
     5     int a[10] = {0};
     6     int i,j,t;
     7     printf("input 10 numbers:
    ");
     8     for (i = 0; i < 10; i++) {
     9         scanf("%d", &a[i]);
    10     }
    11     printf("
    ");
    12     
    13     for (j = 0; j < 9; j++) {
    14         for (i = 0; i < 9 - j; i++) {
    15             if (a[i] > a[i+1]) {
    16                 t = a[i];
    17                 a[i] = a[i+1];
    18                 a[i+1] = t;
    19             }
    20         }    
    21     }
    22     printf("The sorted numbers are:
    ");
    23     for (i = 0; i < 10; i++) {
    24         printf("%d ", a[i]);
    25     }
    26     printf("
    ");
    27 }

    以上是冒泡排序,前提没有要求,测试的数据可以无序。

    而二分法一般要求测试数据先排好序,一般是用于插入或查找一个数据。最后如果出现low > high就Over。

    二分法如下:

     1 #include<stdio.h>
     2 
     3 int main()
     4 {
     5     int a[10] = {-12, 0, 6, 16, 23, 56, 80, 100, 110, 115};
     6     int n, low, high, mid, found;
     7     low = 0;
     8     high = 9;
     9     found = 0;
    10     printf("Input a number to be searched:");
    11     scanf("%d", &n);
    12     
    13     while (low <= high) {
    14         mid = (low + high)/2;
    15         if (n == a[mid]) {
    16             found = 1;
    17             break;
    18         }
    19         else if (n > a[mid]) {
    20             low = mid + 1;
    21         }
    22         else {
    23             high = mid - 1;
    24         }
    25     }
    26     
    27     if (1 == found) {
    28         printf("The index of %d is %d
    ", n, mid);
    29     }
    30     else {
    31         printf("There's no %d
    ", n);
    32     }
    33     
    34     return 0;
    35 }
  • 相关阅读:
    为 Jenkins 配置 .NET 持续集成环境
    树莓派连接GPS模块
    杂记
    大型网站架构系列:电商网站架构案例
    我的心博客。
    555555555555111
    powershell 环境变量只有当前会话起作用问题
    powershell 下独立silent 安装 浏览器问题
    python编码格式
    scss教程推荐
  • 原文地址:https://www.cnblogs.com/whp2011/p/3956420.html
Copyright © 2020-2023  润新知