c 和 Python 實現交換排序,氣泡排序,改進氣泡排序
c:
#include <iostream>
using namespace std;
#define MAXSIZE 10
typedef struct
{
int r[MAXSIZE+1];
int length;
}SqList;
void swap(SqList *L, int i ,int j)
{
int temp =L-> r[i];
L-> r[i]=L-> r[j];
L-> r[j]=temp;
}
//交換排序
void BubbleSort0(SqList *L)
{
int i,j;
for(i=1;i<=L ->length;i++)
{
for (j=i+1;j<=L ->length;j++)
{
if(L-> r[i]>L-> r[j])
{
swap(L,i,j);
}
}
}
}
//氣泡排序
void BubbleSort(SqList *L)
{
int i,j;
for(i=1;i<=L ->length;i++)
{
for (j=L ->length-1;j>=i;j--)
{
if(L-> r[j]>L-> r[j+1])
{
swap(L,j,j+1);
}
}
}
}
//改進氣泡排序
void BubbleSort2(SqList *L)
{
int i,j;
int state=1;
for(i=1;i<=L ->length&&state==1;i++)
{
state=0;
for (j=L ->length-1;j>=i;j--)
{
if(L-> r[j]>L-> r[j+1])
{
swap(L,j,j+1);
state=1;
}
}
}
}
int main()
{
SqList* L = ( SqList* ) malloc( sizeof( SqList ) );//分配記憶體,初始化
L ->length=9;
for(int i=1;i<=L->length;i++)
{
cin>>L ->r[i];
}
for(int i=1;i<=L->length;i++)
{
cout<<L ->r[i];
}
//BubbleSort0(L);
//BubbleSort(L);
BubbleSort2(L);
for(int i=1;i<=L->length;i++)
{
cout<<L ->r[i];
}
}
Python :
L=[9,1,5,8,3,7,4,6,2]
def swap(L,i,j):
temp=L[i]
L[i]=L[j]
L[j]=temp
def BubbleSort0(L):
for i in range (0,len(L)):
for j in range (i+1,len(L)):
if(L[i]>L[j]):
swap(L,i,j)
def BubbleSort(L):
for i in range (0,len(L)):
for j in range (len(L)-2,i-1,-1):
if(L[j]>L[j+1]):
swap(L,j,j+1)
def BubbleSort2(L):
flag= True
for i in range (0,len(L)):
if flag==True:
flag= False
for j in range (len(L)-2,i-1,-1):
if(L[j]>L[j+1]):
swap(L,j,j+1)
flag= True
if __name__ == "__main__":
#BubbleSort0(L)
#BubbleSort(L)
BubbleSort2(L)
print(L)
ps:人生苦短,我用python?