一:冒泡法排序
//冒泡排序 注:從小到大排
//特點:效率低,實現簡單
//思想:每一趟將待排序序列中最大元素移到最后,剩下的為新的待排序序列,重復上述步驟直到排完所有元素。
這只是冒泡排序的一種,當然也可以從后往前排。
算法步驟
-
比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
-
對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。這步做完后,最后的元素會是最大的數。
-
針對所有的元素重復以上的步驟,除了最后一個。
-
持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
動畫演示
參考代碼
public static void bubbleSort(int array[]) {
int t = 0;
for (int i = 0; i < array.length - 1; i++)
for (int j = 0; j < array.length - 1 - i; j++)
if (array[j] > array[j + 1]) {
t = array[j];
array[j] = array[j + 1];
array[j + 1] = t;
}
}
二:選擇排序
//選擇排序 從小到大
//特點:效率低,容易實現。
//思想:每一趟從待排序序列選擇一個最小的元素放到已排好序序列的末尾,剩下的為待排序序列,重復上述步驟直到完成排序。
算法步驟
-
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
-
再從剩余未排序元素中繼續尋找最小(大)元素,然后放到已排序序列的末尾。
-
重復第二步,直到所有元素均排序完畢。
動畫演示
參考代碼
public static void selectSort(int array[]) {
int t = 0;
for (int i = 0; i < array.length - 1; i++){
int index=i;
for (int j = i + 1; j < array.length; j++)
if (array[index] > array[j])
index=j;
if(index!=i){ //找到了比array[i]小的則與array[i]交換位置
t = array[i];
array[i] = array[index];
array[index] = t;
}
}
}
三:插入排序
//插入排序 從小到大
//特點:效率低,容易實現。
//思想:將數組分為兩部分,將后部分元素逐一與前部分元素比較,如果前部分元素比array[i]小,就將前部分元素往后移動。當沒有比array[i]小的元素,即是 合理位置,在此位置插入array[i]
算法步驟
-
將第一待排序序列第一個元素看做一個有序序列,把第二個元素到最后一個元素當成是未排序序列。
-
從頭到尾依次掃描未排序序列,將掃描到的每個元素插入有序序列的適當位置。(如果待插入的元素與有序序列中的某個元素相等,則將待插入元素插入到相等元素的后面。)
動畫演示
參考代碼
public static void insertionSort(int array[]) {
int i, j, t = 0;
for (i = 1; i < array.length; i++) {
if(array[i]<array[i-1]){
t = array[i];
for (j = i - 1; j >= 0 && t < array[j]; j--)
array[j + 1] = array[j];
//插入array[i]
array[j + 1] = t;
}
}
}
四:快速排序
//快速排序 從小到大
//特點:高效,時間復雜度為nlogn。
//采用分治法的思想:首先設置一個軸值pivot,然后以這個軸值為划分基准將待排序序列分成比pivot大和比pivot小的兩部分,
接下來對划分完的子序列進行快排直到子序列為一個元素為止。
算法步驟
-
從數列中挑出一個元素,稱為 “基准”(pivot);
-
重新排序數列,所有元素比基准值小的擺放在基准前面,所有元素比基准值大的擺在基准的后面(相同的數可以到任一邊)。在這個分區退出之后,該基准就處於數列的中間位置。這個稱為分區(partition)操作;
-
遞歸地(recursive)把小於基准值元素的子數列和大於基准值元素的子數列排序;
動畫演示
參考代碼
public static void quickSort(int array[], int low, int high) {// 傳入low=0,high=array.length-1;
int pivot, p_pos, i, t;// pivot->位索引;p_pos->軸值。
if (low < high) {
p_pos = low;
pivot = array[p_pos];
for (i = low + 1; i <= high; i++)
if (array[i] < pivot) {
p_pos++;
t = array[p_pos];
array[p_pos] = array[i];
array[i] = t;
}
t = array[low];
array[low] = array[p_pos];
array[p_pos] = t;
// 分而治之
quickSort(array, low, p_pos - 1);// 排序左半部分
quickSort(array, p_pos + 1, high);// 排序右半部分
}
}
五:測試
package com.svse.paixu;
import java.util.Arrays;
public class JavaSort {
//打印方法
public static void print(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if(i == arr.length-1) {
System.out.println(arr[i] + "]");
}else {
System.out.print(arr[i] + ",");
}
}
}
public static void main(String[] args) {
int[] array = { 37, 47, 23, 100, 19, 56, 56, 99, 9 };
print(array);//排序前
//JavaSort.bubbleSort(array);//冒泡排序
//JavaSort.selectSort(array);//選擇排序
//JavaSort.insertionSort(array);//插入排序
JavaSort.quickSort(array, 0, array.length-1);//快速排序
System.out.println("排序后:" + Arrays.toString(array));
print(array);//排序后
}
}
六:各種排序算法性能比較