package com.larry.sorting;
import java.util.Arrays;
/**
* 冒泡排序
* @author admin
*
*/
public class BubbleSort {
private int[] bubbleSort(int s[]){
if(s == null) return null;
int sLen = s.length;
if(sLen == 0 || sLen == 1) return s;
//冒泡排序核心算法
for(int times = sLen-1; times > 0; times--){
for(int i = 0; i < times-1; i++){
if(s[i] > s[i+1]){ int sym = s[i]; s[i] = s[i+1]; s[i+1] = sym;}
}
}
return s;
}
/**
* 冒泡排序改进算法,加入一个exchange标记(一趟交换开始时值为0;如果结束时还为0说明已经正序,跳出),
* 当有交换时赋值为“前一个数的下标”,
* @param s
* @return
*/
private int[] bubbleSortImp(int s[]){
if(s == null) return null;
int sLen = s.length;
if(sLen == 0 || sLen == 1) return s;
//冒泡排序核心算法
int exchange = 0;
for(int times = sLen-1; times > 0; times--){
for(int i = 0; i < times-1; i++){
if(s[i] > s[i+1]){ exchange = i; int sym = s[i]; s[i] = s[i+1]; s[i+1] = sym;}
}
if(exchange == 0) break;
}
return s;
}
public static void main(String[] args) {
//int array[] = {};
//int array[] = {1};
int array[] = {1, 2, 3, 7, 5, 5, 11};
System.out.println(Arrays.toString(new BubbleSort().
bubbleSort(array)));
}
}
交换排序-冒泡排序
最新推荐文章于 2022-11-27 12:51:57 发布