Java排序算法大概有冒泡排序,选择排序, 插入排序, 归并排序, 快速排序, 堆排序, 桶排序, 希尔排序。
这里先加上我掌握的几种排序算法,之后会补充。
冒泡排序
public class BubbleSort {
public static int[] bubbleSort(int[] A) {
int n = A.length;
for(int i = 0; i < n-1; i++) {
for(int j = i; j < n; j++) {
if(A[i]>A[j]) {
int temp = A[j];
A[j] = A[i];
A[i] = temp;
}
}
}
return A;
}
public static void main(String[] args) {
int[] B = {7, 5, 3, 4, 9, 0, 2};
bubbleSort(B);
for(int i:B) {
System.out.print(i+" ");
}
}
}
插入排序
public class InsertionSort {
public static int[] insertionSort(int[] A) {
int n = A.length;
for(int i = 1; i < n; i++) {
int temp = A[i];
for(int j = i-1; j >= 0 ; j--) {
if(temp<A[j]) {
A[j+1] = A[j];
}else {
break;
}
A[j] = temp;
}
}
return A;
}
public static void main(String[] args) {
int[] B = {7, 5, 3, 4, 9, 0, 2};
System.out.println(Arrays.toString(insertionSort(B)));
}
}
选择排序
public class SelectionSort {
public static int[] selectionSort(int[] A) {
int n = A.length;
for(int i = 0; i < n-1; i++) {
int min = i;
for(int j = i; j < n; j++) {
if(A[min]>A[j])
min = j;
}
int temp = A[min];
A[min] = A[i];
A[i] = temp;
}
return A;
}
public static void main(String[] args) {
int[] B = {7, 5, 3, 4, 9, 0, 2};
System.out.println(Arrays.toString(selectionSort(B)));
}
}
快速排序
package com.rong.sort;
public class QuickSortDemo {
public static void quickSort(int start,int end, int[] arr){
if(start >= end){
return;
}
int base = arr[start];
int i = start+1;
int j = end;
while (i != j){
while( arr[j] > base && i < j) {
j--;
}
while( arr[i] < base && i < j){
i++;
}
//交换
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
//这时i和j相等了
arr[start] = arr[i];
arr[i] = base;
//对左边进行快排
quickSort(start,i-1,arr);
//对右边进行快排
quickSort(i+1,end,arr);
//返回拍好序的数组
}
public static void main(String[] args) {
int[] arr = {3,1,5,3,9,4,7,8};
quickSort(0,6,arr);
for(int data:arr){
System.out.print(data+"\t");
}
}
}