zoukankan      html  css  js  c++  java
  • 折半查找、选择排序在一位数组中的应用

     1 #include<stdio.h>
     2 #define N 10
     3 int main(void) 
     4 {
     5   void select_sort(int *a);
     6   void arry_print(int *a);
     7   void search(int *a,int n);
     8 
     9   int i,number;
    10   int a[N];
    11   printf("Enter matrix:
    ");
    12   for(i=0;i<N;i++)
    13     scanf("%d",&a[i]);
    14   printf("Before sort:
    ");
    15     arry_print(a);    
    16   printf("After sort:
    ");
    17     select_sort(a); 
    18   arry_print(a);
    19   printf("Enter the number you look for:
    ");
    20     scanf("%d",&number);
    21   search(a,number);
    22   return 0;
    23 }
    24 void select_sort(int *a)
    25 {
    26   int i,j,min,t;
    27   for(i=0;i<N-1;i++)
    28   {
    29     min=i;
    30     for(j=i+1;j<N;j++)
    31       if(a[min]>a[j])
    32         min=j;
    33     if(min!=i)
    34     {  
    35 
    36       t=a[i];
    37 
    38       a[i]=a[min];
    39 
    40       a[min]=t;
    41 
    42     }
    43   }    
    44 }
    45 void arry_print(int *a)
    46 {
    47   for(int i=0;i<N;i++)
    48   printf("%d	",a[i]);
    49 }
    50 void search(int *a,int n)
    51 {
    52   int top=0,bott=N-1,mid;
    53   int i,j,k,loca,flag=0;
    54   if(n<a[0]||n>a[N-1])
    55     printf("Cannot find %d.
    ",n);
    56   while((!flag)&&(top<=bott))
    57   {
    58     mid=(top+bott)/2;
    59     if(n==a[mid])
    60     {
    61       loca=mid;
    62       printf("Has found %d,it positon is %d .
    ",n,loca+1);
    63       flag=1;
    64     }
    65     else if(n<a[mid])
    66       bott=mid-1;
    67     else
    68       top=mid+1;
    69   }
    70 }
  • 相关阅读:
    SpringBoot实现原理
    常见Http状态码大全
    forward(转发)和redirect(重定向)有什么区别
    1094. Car Pooling (M)
    0980. Unique Paths III (H)
    1291. Sequential Digits (M)
    0121. Best Time to Buy and Sell Stock (E)
    1041. Robot Bounded In Circle (M)
    0421. Maximum XOR of Two Numbers in an Array (M)
    0216. Combination Sum III (M)
  • 原文地址:https://www.cnblogs.com/sinlearn/p/10539678.html
Copyright © 2011-2022 走看看