代码
算法代码和测试代码如下:
package com.ms.sort;
import org.junit.Test;
/**
* 冒泡排序和选择排序
* 参考https://bbs.csdn.net/topics/250021950
* @author iengchen
* @since 2018-05-01
*/
public class BubbleAndSelectionSort {
/**
* 冒泡排序
* @author iengchen
* @since 2018-05-01
* @param arr
* @return
*/
public int[] bubbleSort(int[] arr) {
int tmp;
for (int i = 1; i < arr.length; i++) {
for(int j=arr.length-1; j>=i; j--) {
if (arr[j] < arr[j-1]) {
tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
@Test
public void testBubbleSort() {
int[] bubbleArr = {3,8,1,5,0,9,7,6};
int[] sortedBubbleArr = bubbleSort(bubbleArr);
for (int i = 0; i < sortedBubbleArr.length; i++) {
System.out.println(i+"-"+sortedBubbleArr[i]);
}
}
/**
* 选择排序
* @author iengchen
* @since 2018-05-01
* @param selecArr
* @return
*/
public int[] selecSort(int[] selecArr) {
for(int i=0; i<selecArr.length-1; i++) {
int tmp = selecArr[i];
int p = i;
for (int j = i+1; j < selecArr.length; j++) {
if (selecArr[j] < tmp) {
tmp = selecArr[j];
p = j;
}
}
selecArr[p] = selecArr[i];
selecArr[i] = tmp;
}
return selecArr;
}
@Test
public void testSelecSort() {
int[] selecArr = {3,8,1,5,0,9,7,6};
int[] sortedSelecArr = selecSort(selecArr);
for (int i = 0; i < sortedSelecArr.length; i++) {
System.out.println(i+"-"+sortedSelecArr[i]);
}
}
}
测试结果
2个排序的测试结果打印如下:
0-0
1-1
2-3
3-5
4-6
5-7
6-8
7-9
网友评论