相邻两数进行比较交换,从0位开始,每次会把最大值“冒泡”到当前最高位部分,
如果不再冒泡(没有交换),则说明有序
#include<stdio.h> void array_printf(int a[],int n); void sort_bubble(int a[],int n); int main(int argc, char const *argv[]) { int i,a[5] = {5,4,3,2,1}; sort_bubble(a,5); array_printf(a,5); return 0; } void array_printf(int a[],int n){ int i ; for (i = 0; i < n; ++i) { printf("%d ",a[i]); } printf("\n"); } void sort_bubble(int a[],int n){ //basic thought: every time switch the neighbour two number until no switch //example: //loop 1: // 0 ~ n-2 : 0 vs 1, 1 vs 2 , 2 vs 3, 3 vs 4,..., n-2 vs n-1 // so, we can get the max to n-1. //loop 2: // 0 ~ n-1 : ... // ... //loop end: // 0 ~ 0 : 0 vs 1 int i,j,t; int s; for( i = n-2 ; i>= 1 ; i--){ s=0; for(j=0 ; j <= i ; j++){ // a[j] vs a[j+1] to see wether tho switch if( a[j] > a[j+1]) { t = a[j]; a[j] = a[j+1]; a[j+1] = t; s++; // record the switch times; } } if(s==0) break; } }
import java.util.List; public class SortBubble implements Sort { @Override public void sort(List<Integer> source) { for(int i = source.size()-2; i >= 0 ; i--){ int times_switch = 0; for(int j = 0 ; j <=i ; j++){ if( source.get(j) > source.get(j+1)){ times_switch ++; list_switch(source, j, j+1); } } if(times_switch == 0) break; } } private void list_switch(List<Integer> source , int i,int j){ if(i>=source.size() || j>=source.size()) return; int t = source.get(i); source.set(i, source.get(j)); source.set(j, t); } }