Last active
May 2, 2017 05:10
-
-
Save claudhu/28b90ff991b843fe311e4fe952b29bf9 to your computer and use it in GitHub Desktop.
如何使用Bubble Sort排序後,運用Binary Search進行搜尋...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Claud Hu | |
* 2017 / 4 / 28 日 | |
*/ | |
import java.util.Scanner; | |
/** 如何使用Bubble Sort排序,然後使用BinarySearch進行搜尋**/ | |
class BubbleSort{ | |
public static void main(String args[]){ | |
final int ARRAY_SIZE = 10; // 建立你要的陣列大小,此處我們使用10個element存放 | |
int [] randomIntArray = new int[ARRAY_SIZE]; // 建立陣列 | |
for(int i = 0 ; i < ARRAY_SIZE ; i++){ | |
randomIntArray[i] = (int) (Math.random()*100); //Push value into Array 我們此處使用 0-99之間範圍的整數 | |
} | |
// 先看看我們的陣列裡面存放的數值 | |
for(int i = 0 ; i < ARRAY_SIZE ; i++){ | |
System.out.printf("%d,",randomIntArray[i]); | |
} | |
System.out.println("\n=====After Sorted=====\n"); //印一行作為排序前以及排序後的區隔 | |
// 這段主要是使用Bubble Sort處理 | |
for(int i = 0 ; i< ARRAY_SIZE ; i++){ // ARRAY_SIZE是常數,我們在前面就已經宣告過。 | |
for(int j = 0 ; j <ARRAY_SIZE-1 ; j++){ // 會使用-1,是因為要避免超出陣列範圍 | |
if(randomIntArray[j] > randomIntArray[j+1]){ | |
// let's swap our value 數值交換,在JAVA的世界裡面,數值交換需要依靠依靠一個【佔存變數】來存放 | |
int temp = randomIntArray[j]; | |
randomIntArray[j] = randomIntArray[j+1]; | |
randomIntArray[j+1] =temp; | |
} | |
} | |
} | |
// 檢核我們修改過後的陣列 | |
for(int i = 0 ; i < ARRAY_SIZE ; i++){ | |
System.out.printf("%d,",randomIntArray[i]); | |
} | |
// 可以開始使用Binary sort搜尋Key的Index | |
Scanner input = new Scanner(System.in); //建立一個Scanner作為 使用者輸入 | |
int key = input.nextInt(); //輸入我們要搜尋的Key | |
int low = 0; // 設定陣列搜尋空間的底部 | |
int height = randomIntArray.length; //設定陣列搜尋的頂部,我們可以透過理解陣列總長來知道其頂部為何 | |
while(low != height){ // 設計一個「非定數回圈」,因為我們不能確定我們的迴圈要走幾次,因此使用While比For好 | |
if(key == randomIntArray[(low+height)/2]){ //如果我們的Key == 陣列的中間值 | |
System.out.printf("index of key is %d",(low+height)/2); | |
break; | |
}else if( key > randomIntArray[(low+height)/2]){ // 如果我們的Key > 陣列的中間值 | |
low = (low+hight) / 2 + 1; // 將搜尋空間的底部移轉成中間值,並且向右偏移一個Element | |
}else if (key < randomIntArray[(low+height)/2]){ // 如果我們的Key < 陣列的中間值 | |
height = ( low + height) / 2 - 1; // // 將搜尋空間的頂部移轉成中間值,並且向左偏移一個Element | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment