zoukankan      html  css  js  c++  java
  • 将各种简单算法组合,使自己更加灵活的使用它

    // 冒泡排序 及二分法查找

    # include <stdio.h>
    # include <stdlib.h>

    void paixu(int *, int);
    int find(int *, int, int);

    int main(void)
    {
     int arry[10];
     int i;
     printf("数组元素: \n");
     for (i = 0; i < 10; ++i)
     {
      arry[i] = rand() % 100;
      printf("%-4d", arry[i]);
     }
     paixu(arry, 10);
     printf("\n排序结果: \n");
     for (i = 0; i < 10; ++i)
     {
      printf("%-4d", arry[i]);
     }
     int target, location;
     printf("\n请输入您想查找的那个数:\n");
     scanf("%d", &target);
     location = find(arry, 10, target);
     if (-1 == location)
     {
      printf("此数组中不存在您想要查找的数!\n");
     }
     else
     {
      printf("您想要查找的数在数组的第 %d 位!\n", location + 1);
     }
     
     return 0;
     }
     
     // 冒泡排序, 从小到大排序
     void paixu(int * seq, int len)
     {
      int temp;
      int i, j;
      for (i = 0; i < len; ++i)
      {
       for (j = 0; j < len-1-i; ++j)
       {
        if (seq[j] > seq[j+1])
        {
         temp = seq[j];
        seq[j] = seq[j+1];
        seq[j+1] = temp;
        }
       
       }
      }
      
      return;
      }
     
      // 二分法查找
      int find(int * seq, int len, int target)
      {
       int low, mid, high;
       low = 0;
       high = len - 1;
       while (low <= high)
       {
        mid = (low + high)/2;
        if (seq[mid] < target)
        {
         low = mid + 1;
        }
      else if (seq[mid] > target)
      {
       high = mid - 1;
      }
      else
          return mid;
       }
       
       return -1;
       }

       /*
           程序输出结果:
             数组元素:
       41  67  34  0   69  24  78  58  62  64
       排序结果:
       0   24  34  41  58  62  64  67  69  78
       请输入您想查找的那个数:
       34
       您想要查找的数在数组的第 3 位!
       
       --------------------------------
       Process exited after 3.412 seconds with return value 0
       请按任意键继续. . .
       */

    转载请注明出处
  • 相关阅读:
    Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
    Leetcode: Flatten Binary Tree to Linked List
    Leetcode: Binary Tree Level Order Transversal II
    Leetcode: Binary Tree Level Order Traversal
    Leetcode: Binary Tree Postorder Transversal
    Leetcode: Binary Tree Inorder Transversal
    Leetcode: Word Break II
    Leetcode: Word Break
    Leetcode: Maximum Subarray
    WDS 三种模式
  • 原文地址:https://www.cnblogs.com/lnlin/p/6531478.html
Copyright © 2011-2022 走看看