【算法学习】排序算法-冒泡排序

思想:

相邻两数进行比较交换,从0位开始,每次会把最大值“冒泡”到当前最高位部分,

如果不再冒泡(没有交换),则说明有序

C语言代码

#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;
	}
}


JAVA代码

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);
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值