2014年5月7日 星期三

排序取最大最小




氣泡排序法從小到大排列,取頭尾(最小最大)值:
#include <stdio.h>

int main() {
 while(1){
  printf("Please enter five integers: ");
  int a[5], i;
  for(i = 0; i < 5; i++){
   scanf("%d", &a[i]);
  }
  
     int j = 0, temp = 0;
     for( i = 0; i < 5; i++) {
         for( j = 0; j < 4 - i; j++) {
             if( a[j] < a[j+1] ) {
                 temp = a[j];
                 a[j] = a[j+1];
                 a[j+1] = temp;
             }
         }
     }
  printf("The largest is %d\nThe smallest is %d\n", a[4], a[0]);
 }
}

列逐次比對,從大排到最小取頭尾(最大最小)值:
#include <stdio.h>

int main(int argc, char *argv[])
{
    int a,b,c,d,e;
    int temp;
    scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
    //大到小
    if(a>b){
         temp = b;
         b = a;
         a = temp;
    }
    if(a>c){
         temp = c;
         c = a;
         a = temp;
    }
    if(a>d){
         temp = d;
         d = a;
         a = temp;
    }
    if(a>e){
         temp = e;
         e = a;
         a = temp;
    }
    //
    if(b>c){
         temp = c;
         c = b;
         b = temp;
    }
    if(b>d){
         temp = d;
         d = b;
         b = temp;
    }
    if(b>e){
         temp = e;
         e = b;
         b = temp;
    }
    if(b>a){
         temp = a;
         a = b;
         b = temp;
    }
    //
    if(c>d){
         temp = d;
         d = c;
         c = temp;
    }
    if(c>e){
         temp = e;
         e = c;
         c = temp;
    }
    if(c>a){
         temp = a;
         a = c;
         c = temp;
    }
    if(c>b){
         temp = b;
         b = c;
         c = temp;
    }
    //
    if(d>e){
         temp = e;
         e = d;
         d = temp;
    }
    if(d>a){
         temp = a;
         a = d;
         d = temp;
    }
    if(d>b){
         temp = b;
         b = d;
         d = temp;
    }
    if(d>c){
         temp = c;
         c = d;
         d = temp;
    }
    //
    if(e>a){
         temp = a;
         a = e;
         e = temp;
    }
    if(e>b){
         temp = b;
         b = e;
         e = temp;
    }
    if(e>c){
         temp = c;
         c = e;
         e = temp;
    }
    if(e>d){
         temp = d;
         d = e;
         e = temp;
    }
    printf("The largest is %d\n",a);
    printf("The smallest is %d\n",e);
}
直接取大小:
#include <stdio.h>

main()
{
 int a1, a2, a3, a4, a5;
 int min, max;
 
 while(1){ 
  printf("Please enter five integers: ");
  scanf("%d%d%d%d%d", &a1, &a2, &a3, &a4, &a5);
  
  min = a1;
  max = a1;
  
  if(a2 > max) max = a2;
  if(a3 > max) max = a3;
  if(a4 > max) max = a4;
  if(a5 > max) max = a5;
  
  if(a2 < min) min = a2;
  if(a3 < min) min = a3;
  if(a4 < min) min = a4;
  if(a5 < min) min = a5;
  
  printf("The largest is %d\n", max);
  printf("The smallest is %d\n\n", min);
 }
}

沒有留言:

張貼留言