Java实现5种不同的排序方法
1、冒泡排序:bubbleSort()
2、选择排序:selectSort()
3、插入排序:insertSort()
4、快速排序:quickSort()
5、归并排序:mergeSort()
import java.util.Arrays;
class Sort{
public static int[] bubbleSort(int[] arr){
for(int i=0; i<arr.length; i++){
for(int j=0; j<arr.length-i-1; j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
public static int[] 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 temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static int[] insertSort(int[] arr){
for(int i=1; i<arr.length; i++){
for(int j=i; j>0; j--){
if(arr[j] < arr[j-1]){
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
else{
break;
}
}
}
return arr;
}
public static void quickSort(int[] arr){
qSort(arr, 0, arr.length - 1);
}
private static int partition(int[] arr, int low, int high){
int pivotkey = arr[low];
while(low < high){
while(low < high && arr[high] >= pivotkey)
high--;
arr[low] = arr[high];
while(low < high && arr[low] <= pivotkey)
low++;
arr[high] = arr[low];
}
arr[low] = pivotkey;
return low;
}
private static void qSort(int[] arr, int low, int high){
if(low < high){
int pivot = partition(arr, low, high);
qSort(arr, low, pivot - 1);
qSort(arr, pivot + 1, high);
}
}
public static void mergeSort(int[] arr){
int[] temp = new int[arr.length];
mSort(arr, 0, arr.length - 1, temp);
}
private static void mSort(int[] arr, int low, int high, int[] temp){
if(low < high){
int mid = (low + high) / 2;
mSort(arr, low, mid, temp);
mSort(arr, mid + 1, high, temp);
merge(arr, low, mid, high, temp);
}
}
private static void merge(int[] arr, int low, int mid, int high, int[] temp){
int p = low, q = mid + 1;
int r = 0;
while(p <= mid && q <= high){
if(arr[p] <= arr[q]){
temp[r++] = arr[p++];
}
else{
temp[r++] = arr[q++];
}
}
while(p <= mid){
temp[r++] = arr[p++];
}
while(q <= high){
temp[r++] = arr[q++];
}
r = 0;
while(low <= high){
arr[low++] = temp[r++];
}
}
public static void prt(int[] arr){
for(int i=0; i<arr.length; i++){
System.out.print(i+":"+arr[i]+" ");
}
System.out.println("");
}
}
public class MySort{
public static void main(String[] args){
int arr[] = {26,15,29,66,99,88,36,77,111,1,6,8,8};
// Sort.bubbleSort(arr);
// Sort.selectSort(arr);
// Sort.insertSort(arr);
// Sort.quickSort(arr);
Sort.mergeSort(arr);
Sort.prt(arr);
}
}