快速排序&二分查找代码实现

阅读更多
/**
 *
 * @author shangyidong
 * @version $Id: BinarySearch.java, v 0.1 2019年05月12日 下午4:53 shangyidong Exp $
 */
public class BinarySearchTest {

    public static void quickSort(int a[], int left, int right) {
        if (left >= right) {
            return;
        }
        int temp = a[left];
        int i = left;
        int j = right;
        while (i != j) {
            while (i < j && a[j] >= temp) {
                j--;
            }
            if (i < j) {
                int t = a[j];
                a[j] = a[i];
                a[i] = t;
            }
            while (i < j && a[i] <= temp) {
                i++;
            }
            if (i < j) {
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
        }
        quickSort(a, left, j - 1);
        quickSort(a, i + 1, right);
    }

    public static int binarySearch(int a[], int key) {
        if (a == null) {
            return 0;
        }
        int left, right, mid;
        left = 0;
        right = a.length - 1;
        while (left <= right) {
            mid = (left + right) / 2;
            if (key > a[mid]) {
                left = mid + 1;
                continue;
            }
            if (key < a[mid]) {
                right = mid - 1;
                continue;
            }
            return mid;
        }
        return -1;
    }

    public static void main(String[] args) {
        int a[] = new int[10];
        System.out.print("原始数组:");
        for (int i = 0; i < 10; i++) {
            a[i] = new Random().nextInt(100);
            System.out.print(a[i] + "  ");
        }
        System.out.println();

        quickSort(a, 0, a.length - 1);
        System.out.print("排序后:");

        for (int i = 0; i < 10; i++) {
            System.out.print(a[i] + "  ");
        }
        System.out.println();
        for (int i = 0; i < 10; i++) {
            int key = a[i];
            System.out.print("查找key=" + key);
            System.out.println(",key下标" + binarySearch(a, key));
        }
    }
}

 

原始数组:82  0  19  20  23  42  56  15  34  52  

排序后:0  15  19  20  23  34  42  52  56  82  

查找key=0,key下标0

查找key=15,key下标1

查找key=19,key下标2

查找key=20,key下标3

查找key=23,key下标4

查找key=34,key下标5

查找key=42,key下标6

查找key=52,key下标7

查找key=56,key下标8

查找key=82,key下标9

你可能感兴趣的:(快速排序&二分查找代码实现)