Java排序算法之二分查找

       /**

        *二分查找特定整数在整型数组中的位置(非递归)

        *查找线性表必须是有序列表

        *@paramdataset

        *@paramdata

        *@returnindex

        */

       public int binarySearch(int[] dataset, int data) {

              int beginIndex = 0;

              int endIndex = dataset.length - 1;

              int midIndex = -1;

              if (data < dataset[beginIndex] || data > dataset[endIndex]

                            || beginIndex > endIndex)

                     return -1;

              while (beginIndex <= endIndex) {

                     midIndex = (beginIndex + endIndex) >>> 1; //相当于midIndex = (beginIndex + endIndex) / 2,但是效率会高些

                     if (data < dataset[midIndex]) {

                            endIndex = midIndex - 1;

                     } else if (data > dataset[midIndex]) {

                            beginIndex = midIndex + 1;

                     } else {

                            return midIndex;

                     }

              }

              return -1;

       }



       public static void main(String[] args) {

              SortTest sortTest = new SortTest();



              int[] array = sortTest.createArray();



              System.out.println("==========冒泡排序后(正序)==========");

              sortTest.bubbleSort(array, "asc");

              System.out.println("==========冒泡排序后(倒序)==========");

              sortTest.bubbleSort(array, "desc");



              array = sortTest.createArray();



              System.out.println("==========倒转数组后==========");

              sortTest.reverse(array);



              array = sortTest.createArray();



              System.out.println("==========选择排序后(正序)==========");

              sortTest.selectSort(array, "asc");

              System.out.println("==========选择排序后(倒序)==========");

              sortTest.selectSort(array, "desc");



              array = sortTest.createArray();



              System.out.println("==========插入排序后(正序)==========");

              sortTest.insertSort(array, "asc");

              System.out.println("==========插入排序后(倒序)==========");

              sortTest.insertSort(array, "desc");



              array = sortTest.createArray();

              System.out.println("==========快速排序后(正序)==========");

              sortTest.quickSort(array, "asc");

              sortTest.printArray(array);

              System.out.println("==========快速排序后(倒序)==========");

              sortTest.quickSort(array, "desc");

              sortTest.printArray(array);



              System.out.println("==========数组二分查找==========");

              System.out.println("您要找的数在第" + sortTest.binarySearch(array, 74)

                            + "个位子。(下标从0计算)");

你可能感兴趣的:(Java排序)