(Java)數組的選擇排序法和二分尋找法實現

來源:互聯網
上載者:User

1、選擇排序法

public class SelectionSort {public static void main(String[] args) {double[] numbers={3,2,5,4,6,8,1,7,9,0};//調用SelectionSort選擇排序方法SelectionSort(numbers);for(int i=0;i<numbers.length;i++)System.out.print(numbers[i]+"  ");System.out.println();char[] chars={'b','a','e','d','c'};//調用java.util.Arrays類中sort排序方法java.util.Arrays.sort(chars);for(int i=0;i<chars.length;i++)System.out.print(chars[i]+"  ");}//選擇排序法(以升序為例),先找到最大數放在列表最後,再在剩下的數中找到最大數,放到剩下這些數最後,如此進行下去public static void SelectionSort(double[] list){for(int i=list.length-1;i>=1;i--){double currentMax=list[0];int currentMaxIndex=0;for(int j=1;j<=i;j++){if(list[j]>currentMax){currentMax=list[j];currentMaxIndex=j;}}if(currentMaxIndex!=i){list[currentMaxIndex]=list[i];list[i]=currentMax;}}}}

運行結果:

0.0   1.0   2.0   3.0   4.0   5.0   6.0   7.0   8.0   9.0 
a   b   c   d   e


2、二分尋找法

public class BinarySearch {public static void main(String[] args) {//已排序的numbers數組int[] numbers={1,2,3,4,5,6,7,8,9};System.out.print(BinarySearch(numbers,3));System.out.println();System.out.print(BinarySearch(numbers,10));System.out.println();//調用java.util.Arrays的binarySearch二分尋找方法System.out.print(java.util.Arrays.binarySearch(numbers, 7));}//二分尋找法,前提是數組已排序//若關鍵字在數組中,則返回該數下標,否則返回(-插入點-1),插入點 被定義為將鍵插入數組的那一點:即第一個大於此鍵的元素索引public static int BinarySearch(int[] list,int key){int low=0;int high=list.length-1;while(low<=high){int mid=(low+high)/2;if(key<list[mid])high=mid-1;else if(key==list[mid])return mid;else low=mid+1;}return -low-1;}}


運行結果:

2

-10

6

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.