冒泡排序
??依次從第一個數(shù)開始依次比較相鄰的兩個數(shù),將小的數(shù)字放在前面,大的數(shù)字放在后面,直到最后一個數(shù),即第一趟完成,重復(fù)此步驟直至全部排序完成。
public class BubbleSort {
public static void main(String[] args) {
int[] arr= {12,23,15,65,43};
bubbleSort(arr);
}
private static void bubbleSort(int[] arr) {
for(int i=1;i<arr.length;i++) {
for(int j=0;j<arr.length-i;j++) {
if (arr[j]>arr[j+1]) {
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
showArray(arr);
}
private static void showArray(int[] arr) {
for(int i:arr) {
System.out.println(i);
}
}
}
直接選擇排序
??第一趟從數(shù)組中找一個最大的數(shù)和數(shù)組最后一個數(shù)交換;第二趟再從數(shù)組中找第二大的數(shù)(即除了最后一位最大的數(shù))和數(shù)組倒數(shù)第二個數(shù)交換;第三趟再從數(shù)組中找除了最后兩個數(shù)最大的數(shù)與倒數(shù)第三個數(shù)交換。。。直到排序完成。
public class SelectSort {
public static void main(String[] args) {
int[] arr= {75,43,66,29,41};
SelectSort sorter=new SelectSort();
sorter.sort(arr);
}
private void sort(int[] arr) {
int index;
for(int i=1;i<arr.length;i++) {
index=0;
for(int j=1;j<=arr.length-i;j++) {
if(arr[j]>arr[index]) {
index=j;
}
}
int temp=arr[arr.length-i];
arr[arr.length-i]=arr[index];
arr[index]=temp;
}
showArray(arr);
}
private void showArray(int[] arr) {
for(int i:arr) {
System.out.println(i);
}
}
}
快速排序
??選定數(shù)組中第一個數(shù)為基準(zhǔn)值,然后定義一個arr[i]從第一個數(shù)向右找到比基準(zhǔn)值小的數(shù)a,再定義一個arr[j]從最后一個數(shù)向左找比基準(zhǔn)值大的數(shù)b,然后a和b交換,然后繼續(xù)上步驟直至a=b,然后將這個位置的數(shù)與基準(zhǔn)值交換,第一趟完成。反復(fù)直至排序完畢。
public class QuickSort {
public static void main(String[] args) {
int[] arr = {12,23,15,65,43,55,42};
quickSort(arr,0,arr.length-1);
}
private static void quickSort(int[] arr, int low, int high) {
if( low > high) {
return;
}
int i = low;
int j = high;
int key = arr[ low ];
while(i<j) {
while(i<j && arr[j] > key){
j--;
}
while( i<j && arr[i] <= key) {
i++;
}
if(i<j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i];
arr[i] = arr[low];
arr[low] = temp;
quickSort(arr, low, i-1 );
quickSort(arr, i+1, high);
showArray(arr);
}
private static void showArray(int[] arr) {
for(int i:arr) {
System.out.println(i);
}
}
}