package com.interview.sort; import java.util.Arrays; //================================================= // File Name : BubbleSort //------------------------------------------------------------------------------ // Author : Common //类名:ArraysBubble //属性: //方法: class ArraysBubble { private int[] arrays; private int curNum; public ArraysBubble(int max) { //建立一个max长度的空数组 super(); arrays = new int[max]; curNum = 0; } public void insert(int value) { //往空的数组里面增加元素 arrays[curNum] = value; curNum++; } public void display() { //显示数组 System.out.println(Arrays.toString(arrays)); } private void swap(int one, int two) { //交换 int temp = arrays[one]; arrays[one] = arrays[two]; arrays[two] = temp; } public void BubbleSort() { for (int i = 0; i < curNum; i++) { for (int j = i + 1; j < curNum; j++) { if (arrays[j] < arrays[i]) { swap(i, j); } } } } // public void BubbleSort() { // int out, in; // for (out = curNum - 1; out > 0; out--) { //curNum自加为下一次插入做做准备,在此应减去1 // for (in = 0; in < out; in++) { //从最后一个数开始,和前面每一个数比较,把最大的移到最后 // if (arrays[in] > arrays[out]) { // swap(in, in + 1); // } // } // } // // // } } //主类 //Function : Bubble_Sort public class BubbleSort { public static void main(String[] args) { // TODO 自动生成的方法存根 int maxSize = 100; ArraysBubble arrays_demo = new ArraysBubble(maxSize); arrays_demo.insert(58); arrays_demo.insert(57); arrays_demo.insert(56); arrays_demo.insert(60); arrays_demo.insert(59); arrays_demo.display(); arrays_demo.BubbleSort(); arrays_demo.display(); } }
输出
[58, 57, 56, 60, 59, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [56, 57, 58, 59, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]