快速排序
时间复杂度 O(n*log2n)
总结起来,快排的核心算法只有两步:
1)sort排序函数中,调用分区函数partition,将大的数组分成两块,然后再分别调用sort函数,这是一个递归过程。
2)partition分区函数
public class QSort { public static void main(String[] args) { quicksort qs = new quicksort(); int data[] = { 44, 22, 2, 32, 54, 22, 88, 77, 99, 11 }; qs.data = data; qs.sort(0, qs.data.length - 1); qs.display(); }}class quicksort { public int data[]; private int partition(int sortArray[], int low, int hight) { int key = sortArray[low]; while (low < hight) { while (low < hight && sortArray[hight] >= key) hight--; sortArray[low] = sortArray[hight]; while (low < hight && sortArray[low] <= key) low++; sortArray[hight] = sortArray[low]; } sortArray[low] = key; return low; } public void sort(int low, int hight) { if (low < hight) { int result = partition(data, low, hight); sort(low, result - 1); sort(result + 1, hight); } } public void display() { for (int i = 0; i < data.length; i++) { System.out.print(data[i]); System.out.print(" "); } }}
二分查找算法
public class BinarySearch { private int rCount=0; private int lCount=0; /** * 获取递归的次数 * @return */ public int getrCount() { return rCount; } /** * 获取循环的次数 * @return */ public int getlCount() { return lCount; } /** * 执行递归二分查找,返回第一次出现该值的位置 * @param sortedData 已排序的数组 * @param start 开始位置 * @param end 结束位置 * @param findValue 需要找的值 * @return 值在数组中的位置,从0开始。找不到返回-1 */ public int searchRecursive(int[] sortedData,int start,int end,int findValue) { rCount++; if(start<=end) { //中间位置 int middle=(start+end)>>1; //相当于(start+end)/2 //中值 int middleValue=sortedData[middle]; if(findValue==middleValue) { //等于中值直接返回 return middle; } else if(findValue>1; //相当于(start+end)/2 //中值 int middleValue=sortedData[middle]; if(findValue==middleValue) { //等于中值直接返回 return middle; } else if(findValue