将冒泡算法写成函数,该函数的输入是数组,该函数的返回是排序后的数组
import java.util.Arrays;
/***
* 冒泡排序
* */
public class BubbleSort {
public static void main(String[] args) {
int a[]={1,8,5,32,45,9,25,36};
BubbleSort.BubbleSort1(a);
}
public static int[] BubbleSort1(int [] arr){
int count=0;
int temp;//临时变量
boolean flag;//是否交换的标志
for(int i=0; i<arr.length-1; i++){
//表示趟数,一共 arr.length-1 次
// 每次遍历标志位都要先置为false,才能判断后面的元素是否发生了交换
flag = false;
for(int j=arr.length-1; j>i; j--){ //选出该趟排序的最大值往后移动
if(arr[j] < arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
flag = true;
}
count++;
}
if(!flag) break;
}
System.out.println(Arrays.toString(arr));
return arr;
}
}
http://t.csdn.cn/dh9Im
这篇是我写了的一些Java基础题,里面有冒泡排序。适合初学者做的,你可以看看,希望对你有帮助
public static int[] bubble(int[] arr) {
int temp = 0;//用于交换的临时变量
for(int i = 0; i<arr.length-1; i++){//外层循环用于排序排几轮
for(int j = 0; j<arr.length-(1+i); j++) {//内层循环用于每一大轮中进行数据交换
if(arr[j] > arr[j+1]) {
//如果前面的数大于后面的,就进行交换
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
这个比较简单,把数组arr作为参数传入函数即可,返回数组,如果需要是直接操作原数组,直接返回原数组即可,如果不操作原数组,先把原数组做个拷贝,然后操作拷贝数组,返回拷贝数组即可,下面的例子是直接操作原数组,参考下面的链接做了一个简单的实现:
参考链接:
冒泡排序(Java)(完整代码)_梁小樽的博客-CSDN博客_java冒泡排序
import java.util.Arrays;
public class SortTest {
//https://blog.csdn.net/weixin_48544279/article/details/125802801
public static int[] sort(int [] arr) {
int temp = 0 ;
//这个用于操作原数组的拷贝数组
// int [] tarr = Arrays.copyOf(arr, arr.length);
// for(int i = 0 ;i< tarr.length -1; i++){
// for(int j = 0; j<tarr.length-1-i; j++){
// if(tarr[j]>tarr[j+1]){
// temp = tarr[j];
// tarr[j] = tarr[j+1];
// tarr[j+1] = temp;
// }
// }
//
// }
// return tarr;
for(int i = 0 ;i< arr.length -1; i++){
for(int j = 0; j<arr.length-1-i; j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
public static void main(String[] args) {
int[] arr = {18,13,50,15,4,17,18};
System.out.println("排序后:");
for(int i = 0; i<arr.length; i++){
System.out.print(arr[i]+"\t");
}
System.out.println();
int[] result=sort(arr);
// TODO Auto-generated method stub
System.out.println("排序后:"); //打印arr数组一样的
for(int i = 0; i<result.length; i++){
System.out.print(result[i]+"\t");
}
}
}
public int[] sort(int[] sourceArray) throws Exception {
// 对 arr 进行拷贝,不改变参数内容
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
for (int i = 1; i < arr.length; i++) {
// 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。
boolean flag = true;
for (int j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = false;
}
}
if (flag) {
break;
}
}
return arr;
}