1.快速排序的其中一种方式挖坑法
public class SortMethod {
public static void main(String[] args) {
int[] a={42,91,33,51,40,39,56,78,55,45,77,42};
int start=0;
int end=a.length-1;
quickSort(a,start,end);
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
private static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// 找寻基准数据的正确索引
int index = sort(arr, low, high);
// 进行迭代对index之前和之后的数组进行相同的操作使整个数组变成有序
quickSort(arr, low, index - 1);
quickSort(arr, index + 1, high);
}
}
private static int sort(int[] a, int low, int high) {
int key = a[low];
while (low < high) {
while (low < high && a[high] >= key) {
--high;
}
a[low] = a[high];
while (low < high && a[low] < key) {
++low;
}
a[high] = a[low];
}
a[low] = key;
return low;
}
}
2.冒泡排序图解
3.选择排序图解
4.插入排序图解
//冒泡排序
@Test
public void BubbleSort(){
int[] r={3,6,5,7,9,2,3,10};
for(int i=0;i<r.length;i++){
for(int j=0;j<r.length-i-1;j++){
if(r[j]>r[j+1]){
int temp=r[j];
r[j]=r[j+1];
r[j+1]=temp;
}
}
}
for(int b=0;b<r.length;b++){
System.out.print(r[b]+" ");
}
}
//选择排序
@Test
public void SelectionSort(){
int[] r={3,6,5,7,9,2,3,10};
for(int i=0;i<r.length;i++){
int min=i;
for(int j=i+1;j<r.length-1;j++){
if(r[min]>r[j]){
min=j;
}
}
int temp=r[i];
r[i]=r[min];
r[min]=temp;
}
for(int b=0;b<r.length;b++){
System.out.print(r[b]+" ");
}
}
//插入排序
@Test
public void InsertionSort(){
int[] r={3,2,5,7,9,6,3,10};
int curValue;
int preIndex;
for(int i=0;i<r.length-1;i++){
curValue=r[i+1];
preIndex=i;
while(preIndex>=0 && curValue<r[preIndex]){
r[preIndex+1]=r[preIndex];
preIndex--;
}
r[preIndex+1]=curValue;
}
for(int b=0;b<r.length;b++){
System.out.print(r[b]+" ");
}
}