java中的幾個簡單排序

------Java培訓、Android培訓、iOS培訓、.Net培訓、期待與您交流! -------

java中的幾個簡單排序

package cn.test;


public class Bubble {
public static void main(String[] args) {
int[] a = { 1, 4, 2, 5, 6, 7 };
xuanZe(a);
System.out.println();
shell(a);
System.out.println();
chaRu(a);
System.out.println();
BubbleSortArray( a);
}
static void BubbleSortArray(int[] a) {
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1])// 比較交換相鄰元素
{
int temp;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i : a) { System.out.print(i+" "); }
}


static void xuanZe(int[] x) {
for (int i = 0; i < x.length; i++) {
int lowerIndex = i;
// 找出最小的一個索引
for (int j = i + 1; j < x.length; j++) {
if (x[j] < x[lowerIndex]) {
lowerIndex = j;
}
}
// 交換
int temp = x[i];
x[i] = x[lowerIndex];
x[lowerIndex] = temp;
}
for (int i : x) {
System.out.print(i + " ");
}
}
// 插入排序
public static void chaRu(int[] x) {
for (int i = 1; i < x.length; i++) {
// i從一開始,因爲第一個數已經是排好序的啦
for (int j = i; j > 0; j--) {
if (x[j] < x[j - 1]) {
int temp = x[j];
x[j] = x[j - 1];
x[j - 1] = temp;
}
}
}
for (int i : x) {
System.out.print(i + " ");
}
}

 

// 希爾排序

 

希爾排序是一種高級排序,它是由插入排序進化來的,插入排序是將未排的數據依次與前面已排好的數據進行比較移動,這樣如果一個較小的數排在靠後的位置,那麼要找到這個數的正確位置就要進行較多次移動。希爾排序改進了這種方式,它將每次比較的間隔擴大,排過一次之後數據就分階段有序了,之後逐漸縮小這個間隔再進行排序。這樣做的目的就是讓數據一開始可以在一個較大的範圍內進行移動,待基本有序後數據的移動量就小了很多

public static void shell(int[] x) {
// 分組
for (int increment = x.length / 2; increment > 0; increment /= 2) {
// 每個組內排序
for (int i = increment; i < x.length; i++) {
int temp = x[i];
int j = 0;
for (j = i; j >= increment; j -= increment) {
if (temp < x[j - increment]) {
x[j] = x[j - increment];
} else {
break;
}
}
x[j] = temp;
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章