java基本排序,java排序

來源:互聯網
上載者:User

java基本排序,java排序

記錄自己整理的幾個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;
}

}

if (start > low) {
quickSort(arr, low, start - 1);

}
if (end < high) {
quickSort(arr, end + 1, high);
}

}

// shell sort,類似選擇排序,只不過有了增量,先粗後細的思想(先粗略排序,再仔細排序)
public static void shellSort(int[] arr) {
int d = arr.length / 2;

while (d >= 1) {
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;

}
}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.