冒泡算法 点击打开链接
冒泡算法应当从教材离开 点击打开链接
基本的算法:
void bubble_sort(int array[],int n)
{
int i,j,flag,temp;
for(i=0;i<n-1;i++)
{
flag=1;
for(j=0;j<n-1-i;j++)
{
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
flag=0;
}
}
if(flag==1)
break;
}
}
改进的算法1:
冒泡排序的基本原理和基本步骤
1. 在每一趟开始之前,先将厨师文件的第N个记录和第N-1个记录的字值进行比较,若发现次序相反(即 R[N-1]>R[N]),则交换记录;
2.由于R[N]和R[N-1]这2个元素已经有序,此时先比较第N-2个记录和第N个记录的值,若为逆序(R[N-2]>R[N]),则将R[N-2]交换到R[N],再将R[N]和R[N-1]一次推进到R[N-1]和R[N-2];否则比较第N-2个记录和第N-1个记录的值,若为逆序(R[N-2]>R[N-1]),则交换这2个记录;
3. 接着依N-2,N-1为双泡,和N-3比较,同步骤2一样;依次类推,直到第3个,第2个,和第1个之间的比较为止,那么经过这一次的排序,位置1,2 则为最小的2个元素,那么对剩下的N-2个值进行第二次排序,最小的则为,第3,4个,重复进行不超过 N/2次,则整个过程结束;
算法及代码如下:
#include "stdafx.h"
#include <stdio.h>
#include<iostream>
void bubble_sort(int str[],int n)
{
int i,j,temp;
int *tt=str;
n=n-1;
for(i=0;i<n/2;i++)
{
if(tt[n]<tt[n-1])
{
temp=tt[n];
tt[n]=tt[n-1];
tt[n-1]=temp;
}
for(j=n-2;j>=i;j--)
{
if(tt[j+2]<tt[j])
{
temp=tt[j];
tt[j]=tt[j+1];
tt[j+1]=tt[j+2];
tt[j+2]=temp;
}
else if(tt[j+1]<tt[j])
{
temp=tt[j];
tt[j]=tt[j+1];
tt[j+1]=temp;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int len;
int i;
int tmp[10]={1,3,5,8,6,7,0,4,9,2};
len=10;//strlen(tmp);
for(i=0;i<10;i++)
{
printf("%d\n",tmp[i]);
}
bubble_sort(tmp,len);
std::cout<<std::endl;
for(i=0;i<10;i++)
{
printf("%d\n",tmp[i]);
}
getchar();
return 1;
}
3、
//奇偶冒泡排序
void OddEvenSort( int a[], int n )
{
int i, tmp, tag=1; //tag=1为发生了交换的标志
do
{
tag = 0; //设奇数趟无交换
for( i=1; i<n-1; i+=2 ) //扫描所有奇数项
{
if( a[i] > a[i+1] )
{
tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
tag = 1;
}
}
tag = 0; //设偶数趟无交换
for( i=0; i<n-1; i+=2 ) //扫描所有偶数项
{
if( a[i] > a[i+1] )
{
tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
tag = 1;
}
}
}
while( tag );
}
奇偶冒泡排序是每一趟都是扫描奇数项,交换相邻的两项元素,然后扫描偶数项,交换相邻的元素。
4. 局部冒泡排序(需要改进)
void bubble_sort(int str[],int len)
{
int i,j,temp,flag=0;
for(i=0;i<len-1;i++)
{
if(str[i]>str[i+1])
{
temp=str[i];
str[i]=str[i+1];
str[i+1]=temp;
bubble_sort(str,i+1);
}
}
}