算法

来源:互联网 发布:手机按键连发软件 编辑:程序博客网 时间:2024/06/11 04:53

1. 求一组数据中的最大值:两两比较

#include<stdio.h>

void main(void)
{
 int aa[10]={0,1,3,4,7,7,0};
 int max;

 max=aa[0];
 for(int i=1;i<7;i++)
 {
  if(max<aa[i])
  {
   max=aa[i];
  }
 }
 printf("%d\n",max);

}

2.矩阵乘法

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

void main(void)
{
 int temp[10][10];
 int i,j,k;
 int array[10][10];

 for(i=0;i<10;i++)
 {
  for(j=0;j<10;j++)
  {
   temp[i][j]=i+j;
  }
 }
 for(i=0;i<10;i++)
 {
  for(j=0;j<10;j++)
  {
   array[i][j]=0;
   for(k=0;k<10;k++)
   {
    array[i][j]+=temp[i][j]*temp[k][j];
   }
   printf("%-6d",array[i][j]);
  }
  printf("\n");
 }
}

 

3.冒泡算法(从小到大算法)

(1)大数上浮或小数上浮

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

void main(void)
{
 int temp[10]={7,2,5,9,10,5,6,4,3,5};
 int n=10;
 int i,j;
 int tp;

 for(i=0;i<n-1;i++)
 {
  for(j=i+1;j<n-1;j++)
  {
   if(temp[i]>temp[j])
   {
    tp=temp[i];
    temp[i]=temp[j];
    temp[j]=tp;
   }
  }
  printf("%-5d",temp[i]);
 }
 printf("\n");
}

(2)

小数下沉或大数下沉算法

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

void main(void)
{
 int temp[10]={7,2,5,9,10,5,6,4,3,5};
 int n=10;
 int i,j;
 int tp;

 for(i=n-1;i>0;i--)
 {
  for(j=0;j<i;j++)
  {
   if(temp[j]>temp[j+1])
   {
    tp=temp[j];
    temp[j]=temp[j+1];
    temp[j+1]=tp;
   }
  }
  
 }
 for(i=0;i<n;i++)
  printf("%-5d",temp[i]);
 printf("\n");
}

 (3)改进型的冒泡算法:如果之前就是有序的,则停止比较

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

void main(void)
{
 int temp[10]={10,2,3,4,5,6,7,8,9,10};
 int n=10;
 int i,j;
 int tp;
 int change=1;
 int k=0;

 for(i=n-1;i>0 && change ;i--)            //发现无交换则直接退出
 {
  change=0;               
  for(j=0;j<i;j++)
  {
   if(temp[j]>temp[j+1])
   {
    tp=temp[j];
    temp[j]=temp[j+1];
    temp[j+1]=tp;
    change=1;                   //发现有交换
   }
   k++;
  }
  
 }
 for(i=0;i<n;i++)
  printf("%-5d",temp[i]);
 printf("\ncount:%d\n",k);
}

 

原创粉丝点击