网上容易找到C/C++实现的排序算法,Java的虽然有,不过大都过于繁琐。这段时间因为准备面试,在网上查找了一些排序算法的Java版,整理在此。
1.冒泡排序
时间复杂度O(n^2),稳定度:稳定。
public static void bubbleSort(int[] input) {
for(int i = 0; i < input.length; ++i) {
for(int j = 0; j < input.length - i - 1; ++j) {
if(input[j] > input[j + 1]) {
//交换
int temp = input[j];
input[j] = input[j + i];
input[j + 1] = temp;
}
}
}
}
2.选择排序
时间复杂度O(n^2),稳定度:不稳定。
public static void selectionSort(int[] input) {
for(int i = 0; i < input.length; ++i) {
int minIndex = i;
for(int j = i; j < input.length; ++j) {
if(input[j] < input[minIndex]) {
minIndex = j;
}
}
if(minIndex != i) {
//交换
int temp = input[i];
input[i] = input[minIndex];
input[minIndex] = temp;
}
}
}
3.插入排序
时间复杂度O(n^2),稳定度:稳定。
public static void insertionSort(int[] input) {
for(int i = 1; i < input.length; ++i) {
for(int j = i; j > 0; --j) {
if(input[j] < input[j - 1]) {
//交换
int temp = input[j];
input[j] = input[j - 1];
input[j - 1] = temp;
}
}
}
}
写完代码后发现,插入排序跟冒泡排序好像,只不过冒泡是依此向上(向后)进行交换,而插入是向下(向前)。
4.快速排序
时间复杂度O(nlogn),稳定度:不稳定。
public static void quickSort(int[] input, int low, int high) {
if(low < high) {//递归终止条件
int pivot = partition(input, low, high);
quickSort(input, low, pivot - 1);
quickSort(input, pivot + 1, high);
}
}
public static int partition(int[] input, int low, int high) {
int key = input[low];
while(low < high) {
while(low < hign && input[high] > key) {//此处,必需先从high开始向下遍历。
--high;
}
input[low] = input[high];
while(low < high && input[low] < key) {
++low;
}
input[high] = input[low];
}
input[low] = key;
return low;
}
5.归并排序
时间复杂度O(nlogn),稳定度:稳定。
public static void mergeSort(int[] input, int low, int high) {
if(low < high) {
int mid = (high - low) / 2;
mergeSort(input, low, mid);
mergeSort(input, mid + 1, high);
merge(input, low, mid, high);
}
}
public static void merge(int[] input, int low, int mid, int high) {
int i = low, j = mid + 1, k = 0;
int[] temp = new int[high - low + 1];
while(i <= mid && j <= high) {
if(input[i] < input[j]) {
temp[k++] = input[i++];
}else{
temp[k++] = input[j++];
}
}
while(i <= mid) {
temp[k++] = input[i++];
}
while(j <= high) {
temp[k++] = input[j++];
}
for(i = 0; i < temp.length; ++i) {
input[low + i] = temp[i];
}
}
6.堆排序
时间复杂度O(nlogn),稳定度:不稳定。