基本排序算法
冒泡排序
package com.sort;
public class BubbleSort {
public static void main(String[] args) {
int n [] ={2,3,1,9,6,4};
for (int i = 0; i < n.length-1; i++) {
for (int j = 0; j < n.length-1-i; j++) {
if (n[j+1] < n[j]) {
int temp = n[j];
n[j] = n[j+1];
n[j+1] = temp;
}
}
}
for (int i = 0; i < n.length; i++) {
System.out.println(n[i]);
}
}
}
选择排序
package com.sort;
public class ChooseSort {
public static void main(String[] args) {
int[] n = {2,3,1,9,6,4};
for (int i = 0; i < n.length ; i++) {
for (int j = i+1; j < n.length ; j++) {
int min = i;
if ( n[j] < n[min]) {
min = j;
int temp = n[i];
n[i] = n[min];
n[min] = temp;
}
}
}
for (int i = 0; i < n.length ; i++) {
System.out.println(n[i]);
}
}
}
插入排序
package com.sort;
public class InsertSort {
public static void main(String[] args) {
int[] n = {12,1,5,9,1,4};
for (int i = 1; i < n.length; i++) {
int temp = n[i];
for (int j = i-1; j >= 0; j--) {
if (temp < n[j]) {
n[j+1] = n[j];
if (j == 0) {
n[0] = temp;
}
} else {
n[j+1] = temp;
break;
}
}
}
for (int i = 0; i < n.length; i++) {
System.out.println(n[i]);
}
}
}