【算法学习】排序算法-冒泡排序
2014-11-25 22:20
330 查看
思想:
相邻两数进行比较交换,从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); } }
相关文章推荐
- java排序算法学习(一)--冒泡排序
- 算法学习-排序算法-快速排序
- 算法学习笔记之冒泡排序
- 黑马程序员—Java基础学习笔记之排序算法:选择排序&冒泡排序
- 黑马程序员_java基础学习笔记之排序算法(选择排序、冒泡排序
- c# 数据结构算法学习一:冒泡排序
- 算法学习 - 归并排序,快速排序,冒泡排序
- 排序算法学习——冒泡排序
- 算法学习小心得——基于比较的排序算法汇总
- 算法学习与实践之冒泡排序
- C#数据结构和算法学习系列四----基础排序算法
- 算法学习一之常见的七大排序算法
- 算法学习一之常见的七大排序算法
- 算法学习之冒泡排序,6174问题
- [算法学习]常用排序算法实现
- 【算法学习】浅谈排序算法
- STL学习笔记----14.STL算法之 (排序算法)
- 排序算法-对冒泡排序的优化改进算法
- 一步步学习数据结构和算法之冒泡排序效率分析及java实现
- 算法分析学习笔记(三) - 排序算法(上)