- 选择排序
从所有序列中先找到最小的,然后放到第一个位置。之后再看剩余元素中最小的,放到第二个位置……以此类推,就可以完成整个的排序工作了
package sxd.learn.java;
/**
*
* @author lab
*
*/
public class SelectionSort {
public static void main(String[] args) {
int[] iArray = {0};
selectionSort(iArray);
for (int element : iArray) {
System.out.print(element + " ");
}
System.out.println();
}
/**
* 选择排序
* @param iArray
*/
public static void selectionSort(int[] iArray){
if(iArray.length == 0 || iArray.length == 1)
return ;
int min = 0;
int index = 0;
for (int i = 0; i < iArray.length; i++) {
min = iArray[i];
index = i;
for (int j = i + 1; j < iArray.length; j++) {
if(iArray[j] < min){
min = iArray[j];
index = j;
}
}
exchange(iArray, i, index);
}
}
/**
* 交换两个数
*/
public static void exchange(int[] iArray, int i, int j){
int temp = iArray[i];
iArray[i] = iArray[j];
iArray[j] = temp;
}
}
- 冒泡排序
冒泡排序就是比较相邻的元素大小,将小的前移,大的后移,就像水中的气泡一样,最小的元素经过几次移动,会最终浮到水面上。
package sxd.learn.java;
/**
*
* @author lab
*
*/
public class BubbleSort {
public static void main(String[] args) {
int[] iArray = {5, 3, 4, 8, 2, 1, 0, -2, -1};
print(iArray);
bubbleSort(iArray);
}
/**
* 冒泡排序
*/
public static void bubbleSort(int[] iArray){
boolean exchange = false;
if(iArray.length == 0 || iArray.length == 1)
return ;
for (int i = 0; i < iArray.length; i++) {
exchange = false;
for (int j = iArray.length - 1; j > i; j--) {
if(iArray[j] < iArray[j - 1]){
exchange = true;
exchange(iArray, j, j - 1);
}
}
print(iArray);
if(!exchange)
break;
}
}
/**
* 交换两个数
*/
public static void exchange(int[] iArray, int i, int j){
int temp = iArray[i];
iArray[i] = iArray[j];
iArray[j] = temp;
}
public static void print(int[] iArray){
for (int element : iArray) {
System.out.print(element + " ");
}
System.out.println();
}
}