記錄自己整理的幾個java排序代碼
public class Index {
public static void main(String[] args) {
#int[] a = { 1, 4, 5, 6, 8, 2, 3, 9, 6, };
// selectSort(a);
// bubleSort(a);
// insertSort(a);
// quickSort(a, 0, a.length - 1);
// quickSort(a, 0, a.length - 1);
shellSort(a) ;
for (int b : a) {
System.out.println(b);
}
}
// select sort,從後面的列表中選出最大的放到前面
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] < arr[j]) {
int tem = arr[ j];
arr[j] = arr[i];
arr[i] = tem;
}
}
}
}
// buble sort,子迴圈中,兩兩比較交換,形似冒泡,從而將大的數放到後面
public static void bubleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
# for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int tem = arr[j + 1];
arr[j + 1] = arr[j];
arr [j] = tem;
}
}
}
}
# // insert sort,假定前面的是有序的,子循環中,用目標元素和前面的比較,遇到大的就向前移動,遇到小的就插入該位置
public static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = i;
int temp = arr[i];
while (j > 0) {
if (temp < arr[j - 1]) {
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
j--;
}
}
}
# // quick sort,類似折半的思想,讓某個值左邊的都小於它,右邊的都大於它,然後兩邊遞歸
public static void quickSort(int[] arr, int low, int high) {
int start = low;
int end = high;
int key = arr[start];
while (end > start) {
while (end > start && arr[end] >= key) {
end --;
}
if (arr[end] <= key) {
int tem = arr[end];
arr[end] = arr[start];
arr [start] = tem;
}
while (start < end && arr[start] <= key) {
start++;
}
if (arr[start] > = key) {
int tem = arr[start];
arr[start] = arr[end];
arr[end] = tem;
}
quickSort(arr, low, start - 1);
if (end < high) {
quickSort( arr, end + 1, high);
}
public static void shellSort(int[] arr) {
int d = arr.length / 2;
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length - d; j = j + d) {
if (arr [j] > arr[j + d]) {
int tem = arr[j];
arr[j] = arr[j + d];
arr[j + d] = tem ;
}
}
}
d = d / 2;
}
以上是java基本排序實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!