一、快排
import org.junit.Test; import java.util.Arrays; public class QuickSort { @Test public void test(){ int [] tar = {54,45,87,12,95,56,32,15,0,25}; quickSort(tar, 0 , tar.length-1); System.out.println(Arrays.toString(tar)); } public void quickSort(int[] target, int low, int high){ if(low >= high) return; if(low < high){ int pivotLocation = getPivotLocation(target, low, high); //分为两部分,分别递归处理 quickSort(target,low,pivotLocation-1); quickSort(target,pivotLocation+1,high); } } //获取一个枢纽点,使得在它前面的元素均比它小,在它后面的元素均比它大 public int getPivotLocation(int[] target, int low, int high){ if(low >= high) return -1; int pivotNum = target[low];//默认是target[low]作为基准数,满足上述条件 while(lowwhile(low < high && target[high] >= pivotNum) high--; //循环不满足条件,则将high对应位置与low交换 target[low]=target[high]; while(low < high && target[low] <= pivotNum) low++; //同理 target[high] = target[low]; } //将pivotNum放在它改在的位置 target[low] = pivotNum; return low; } }
二、归并
import org.junit.Test; import java.util.Arrays; public class MergeSort { @Test public void test(){ int [] tar = {54,45,87,12,95,56,32,15,0,25}; msort(tar, 0 , tar.length-1); System.out.println(Arrays.toString(tar)); } public void msort(int[] target, int low, int high){ int mid = (low + high)/2; if(low//左右两部分不断的切分 msort(target,low, mid); msort(target,mid+1,high); //切分完毕,进行mergesort mergeSort(target,low,mid,high); } } public void mergeSort(int[] target, int low, int mid, int high){ //对数组low - mid 和mid+1 - high 两部分合并排序 int [] temp = new int[high-low+1];//临时数组,存储中间结果 int i= low;//记录第一部分 int j = mid+1;//记录第二部分 int k=0;//记录temp数组指针 while(i <= mid && j <= high){ if(target[i] <= target[j]){ temp[k++] = target[i++]; }else{ temp[k++] = target[j++]; } } //循环结束,判断将剩余的元素放入 while(i <= mid){ temp[k++] = target[i++]; } while(j <= high){ temp[k++] = target[j++]; } //遍历临时数组,将临时数组覆盖原数组的元素 for(int x=0; x length;x++){ target[x+low] = temp[x]; } } }
三、插入排序
import java.util.Arrays; public class InsertSort { public static void main(String [] args){ int [] tar = {54,45,87,12,95,56,32,15,0,25}; //默认首元素已经有序 for(int i=1;ilength;i++){ //把当前待排序的元素存入临时变量 int temp = tar[i]; int j =i;//临时指针 while(j > 0 && tar[j-1] > temp){ //滑动 tar[j] = tar[j-1]; j--; } //找到位置之后,将临时变量赋值回去 tar[j] = temp; } System.out.println(Arrays.toString(tar)); } }
四、二分查找
public class BinarySearch { @Test public void test(){ int [] tar = {0, 12, 15, 25, 32, 45, 54, 56, 87, 95}; int res = getLocation(tar, 3); System.out.println(res); System.out.println( res== -1? "未找到": tar[res]); } public int getLocation(int [] tar, int target){ int low = 0; int high = tar.length - 1; int mid; while(low <= high){ mid = (low+high)/2; if(target < tar[mid]){ high = mid -1; }else if(target > tar[mid]){ low = mid + 1; }else{ return mid; } } return -1; } }