想写一个冒泡法排序,没什么思路,就先写了个java的
public static void main(String[] args) {
int array[] = {88,2,43,12,34,8,67,33,99};
for (int i = 0; i < array.length -1; i++){
for(int j = 0 ;j < array.length - i - 1; j++){
if(array[j] < array[j + 1]){
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.print("第" + (i + 1) + "次排序:");
for(int a = 0; a < array.length; a++){
System.out.print(array[a] + "\t");
}
System.out.println("");
}
System.out.print("最终排序:");
for(int a = 0; a < array.length; a++){
System.out.print(array[a] + "\t");
}
}
写完之后,看了看,就是2个循环:
1.内层循环比较相邻2个数的大小,如果后面的大,就交换这两个数;
2.外层循环是对每个未被排序的数重复进行过程1的比较;
根据这两步,回想一下python的语法,设计python冒泡法排序
array=[88,2,43,12,34,8,67,33,99]
array_new=[]
for i in range(len(array)-1):
print("第%s次排序"%(i+1),array)
for j in range(len(array)-i-1):
if(array[j]<array[j+1]):
array[j],array[j+1]=array[j+1],array[j]
print("最终排序",array)