Created
August 21, 2020 13:58
-
-
Save Peters8090/076809e34dc642923217fefc3bb6738b to your computer and use it in GitHub Desktop.
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
package programowanie_komputerowe; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Hashtable; | |
import java.util.List; | |
public class BinSearch { | |
public static void main(String[] args) | |
{ | |
List<Integer> list = new ArrayList<Integer>( | |
Arrays.asList(2, 5, 6, 8, 11, 12, 13)); | |
List<Integer> tempList = list; | |
int x = 6; | |
while(tempList.size() > 1) | |
{ | |
if(tempList.get(getMedianIndex(tempList)) == x) | |
{ | |
System.out.println("x found at index " + getMedianIndex(list)); | |
return; | |
} | |
tempList = splitList(tempList, getMedianIndex(tempList), getMedianIndex(tempList) > x); | |
} | |
System.out.println("x does not exist in this list"); | |
} | |
static int getMedianIndex(List<Integer> list) | |
{ | |
if((list.size() / 2) % 2 == 0) | |
return list.size() / 2 - 1; | |
else | |
return (int) (list.size() / 2 + 0.5f); | |
} | |
static List<Integer> splitList(List<Integer> list, int median, Boolean toLeft) | |
{ | |
if(toLeft) | |
{ | |
for(int i = median; i >= 0; i--) | |
{ | |
list.remove(i); | |
} | |
} | |
else | |
{ | |
for(int i = median; i <= list.size() - 1; i++) | |
{ | |
list.remove(i); | |
} | |
} | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment