排序是将一组“无序”的记录序列调整为“有序”的序列的操作。最简单的排序算法有选择排序、冒泡排序和插入排序。
public class popSort {
public static void printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
// 选择法排序
public static void selectSort(int[] a) {
if(a ==null || a.length<2){
return ;
}
for (int i = 0; i < a.length; i++) {
int min = i;
for (int j = i; j < a.length; j++) {
if (a[min] > a[j]) {
min = j;
}
}
if (min != i) {
int tmp = a[i];
a[i] = a[min];
a[min] = tmp;
}
}
}
// 冒泡法排序, 从右到左
public static void bubbleSort1(int[] a) {
if(a ==null || a.length<2){
return ;
}
for (int i = 0; i < a.length; i++) {
for (int j = a.length-1; j > i; j--) {
if (a[j] < a[j - 1]) {
int tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
}
}
}
}
// 冒泡法排序, 从左到右
public static void bubbleSort2(int[] a) {
if(a ==null || a.length<2){
return ;
}
for (int i = 0; i < a.length; i++) {
for(int j =0; j<a.length-1;j++){
if(a[j]>a[j+1]){
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
// 冒泡法排序, 从右到左
public static void advBubbleSort1(int[] a) {
if(a ==null || a.length<2){
return ;
}
boolean exchange = true;
for (int i = 0; (i < a.length) && exchange; i++) {
exchange = false;
for (int j = a.length-1; j > i; j--) {
if (a[j] < a[j - 1]) {
int tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
exchange = true;
}
}
}
}
// 冒泡法排序, 从左到右
public static void advBubbleSort2(int[] a) {
if(a ==null || a.length<2){
return ;
}
boolean exchange = true;
for (int i = 0; (i < a.length) && exchange; i++) {
exchange = false;
for(int j =0; j<a.length-1;j++){
if(a[j]>a[j+1]){
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
exchange = true;
}
}
}
}
// 插入排序
public static void insertSort(int[] a) {
if(a ==null || a.length<2){
return ;
}
for(int i =0; i<a.length;i++){
int currentValue = a[i];
int postion = i;
for(int j = i-1;j>=0;j--){
if(a[j]>currentValue){
a[j+1] = a[j];
postion = j;
}
else{
break;
}
}
a[postion] = currentValue;
}
}
public static void main(String[] args) {
int[] a = { 2, 11, 3, 12, 54, 23, 17, 45, 3, 26, 17, 10, 20, 51, 28 };
System.out.println("排序前:");
printArray(a);
// selectSort(a);
//bubbleSort1(a);
//bubbleSort2(a);
//advBubbleSort1(a);
//advBubbleSort2(a);
insertSort(a);
System.out.println("排序后:");
printArray(a);
<span style="white-space:pre"> </span>}
}