学习排序算法,自己写了一个,结果写完发现跟经典的冒泡算法不一样。
经典的冒泡算法是先把最大的找出来,放到最后,bubble
我的是先把最小的找出来,放到最前面,这应该都是一个变种吧。bubble
void bubble1(int *number,int count) //大的往下
{
int i,j,k=0; //循环次数控制
int m; //打印数组控制
int temp; //临时变量
bool ischanged;
for ( i=count; i>0;i--)
{
ischanged=false;
printf("bubble1第%d遍结果:",count-i);
for ( j=0;j<i-1;j++)
if (number[j]>number[j+1])
{
temp=number[j];
number[j]=number[j+1];
number[j+1]=temp;
ischanged=true;
}
if(!ischanged)
{
break;
}
for ( m=0;m< count;m++)
printf("%d,",number[m]);
printf("\n");
}
printf("bubble 排序后");
printf("[");
for (int i=0;i<count;i++)
{
printf("%d,",number[i]);
}
printf("]");
}
void bubble(int *number,int count) //小的往上
{
int i,j,k=0; //循环次数控制
int m; //打印数组控制
int temp; //临时变量
bool ischanged;
for ( i=0;i< count;i++)
{
ischanged=false;
printf("bubble第%d遍结果:",i);
for ( j=i+1;j<count;j++)
if (number[i]>number[j])
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
ischanged=true;
}
if(!ischanged)
{
break;
}
for ( m=0;m< count;m++)
printf("%d,",number[m]);
printf("\n");
}
printf("bubble 排序后");
printf("[");
for (int i=0;i<count;i++)
{
printf("%d,",number[i]);
}
printf("]");
}
结果
还有选择排序,这个是看的经典的啦
思路就是先把最小的下表找出来,然后交换,这样效率就高了
void select(int *number,int count)
{
int i,j,k=0; //循环次数控制
int m; //打印数组控制
int temp; //临时变量
for ( i=0;i< count;i++)
{
k=i;
printf("select第%d遍结果:",i);
for ( j=i+1;j<count;j++)
if (number[k]>number[j])
k=j;
if(k!=i)
{
temp=number[i];
number[i]=number[k];
number[k]=temp;
}
for ( m=0;m< count;m++)
printf("%d,",number[m]);
printf("\n");
}
printf("select 排序后");
printf("[");
for (int i=0;i<count;i++)
{
printf("%d,",number[i]);
}
printf("]");
}
结果
来个主函数
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
void size();
void avg( int * number,int count);
void select(int *number,int count);
void bubble(int *number,int count);
void bubble1(int *number,int count);
void main()
{
int number[]={11,10,9,8,7,1,5,4,3,2,6};
// int number[]={11,2,3,4,5,6,7,8,9,10,1};
int count =sizeof(number)/sizeof(int);
printf("count = %d\n",count);
// string b=NULL;
avg(number,count);
// printf("avg = %.3f\n",b);
printf("select排序前\n");
printf("[");
for (int i=0;i<count;i++)
{
printf("%d,",number[i]);
}
printf("]");
printf("\n");
select(number,count);
printf("\n");
//int number1[]={11,10,9,8,7,6,5,4,3,2,1};
int number1[]={11,2,8,4,33,55,7,3,9,10,1};
//int number1[]={11,10,9,8,7,1,5,4,3,2,6};
printf("bubble排序前\n");
printf("[");
for (int i=0;i<count;i++)
{
printf("%d,",number1[i]);
}
printf("]");
printf("\n");
bubble(number1,count);
printf("\n");
//size();
int number2[]={11,2,8,4,33,55,7,3,9,10,1};
//int number1[]={11,10,9,8,7,1,5,4,3,2,6};
printf("bubble1排序前\n");
printf("[");
for (int i=0;i<count;i++)
{
printf("%d,",number2[i]);
}
printf("]");
printf("\n");
bubble1(number2,count);
printf("\n");
}
ok, 两天的学习结果。
还有知道int,char等的占得字节数用sizeof(int)。