java冒泡排序

来源:互联网 发布:mac audition 破解 编辑:程序博客网 时间:2024/06/04 00:28
package sort;import java.util.Random;/** * 依次比较相邻的两个数,将小数放在前面,大数放在后面   * 冒泡排序,具有稳定性   * 时间复杂度为O(n^2) * 不及堆排序,快速排序O(nlogn,底数为2)   * @author e421083458 *  */public class BubbleSort{public static void main(String args[]){Random ran = new Random();int[] sort = new int[10];for(int i=0;i<10;i++){sort[i] = ran.nextInt(50);}System.out.println("排序前的数组为");for(int i:sort){System.out.println(i+""); }buddleSort(sort);System.out.println();System.out.print("排序后的数组为");for(int i:sort){System.out.println(i+"");}}private static void buddleSort(int[] sort){for(int i=1;i<sort.length;i++){//外层只做循环//内层循环,只能操作相邻两个元素, 所以需要借助外层for(int j=0;j<sort.length-1;j++){//内层操作实际数据if(sort[j]>sort[j+1]){int temp = sort[j+1];sort[j+1] = sort[j];sort[j] = temp;}}}}}

原创粉丝点击