二分查找和交替打印100以内的奇偶数
二分查找
GO实现,与JAVA基本没有区别:
GO:
func BinarySearch(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
low := 0
high := n - 1
for low <= high {
mid := (low + high) >> 1
if a[mid] == v {
return mid
} else if a[mid] > v {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
//递归实现
func BinarySearchRecursive(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}
return bs(a, v, 0, n-1)
}
func bs(a []int, v int, low, high int) int {
if low > high {
return -1
}
mid := (low + high) >> 1
if a[mid] == v {
return mid
} else if a[mid] > v {
return bs(a, v, low, mid-1)
} else {
return bs(a, v, mid+1, high)
}
}
func main() {
arr:= []int{1,4,12,35,14,11}
//key := 2
key := 4
//a := BinarySearch(arr, key)
a :=BinarySearchRecursive(arr, key)
if a == -1 {
fmt.Println("查找的是",key,",序列中没有该数")
}else{
fmt.Println("查找的是",key,",找到在数组中的位置坐标为",a)
}
}
JAVA:
package com.csq.study;
public class BinarySearch {
public static int BinarySearch(int[] arr,int key){
int low = 0;
int high = arr.length - 1;
if(arr.length == 0){
return -1;
}
while(low <= high){
int middle = (low + high) >> 1;
if(arr[middle] > key){
high = middle - 1;
}else if(arr[middle] < key){
low = middle + 1;
}else{
return middle;
}
}
return -1;
}
//递归实现
public static int BinarySearchRecursive(int[] arr,int key,int low,int high){
if( low > high){
return -1;
}
int middle=(low + high) >> 1;
if(arr[middle] > key){
return BinarySearchRecursive(arr, key, low, middle - 1);
}else if(arr[middle] < key){
return BinarySearchRecursive(arr, key, middle + 1, high);
}else {
return middle;
}
}
public static void main(String[] args) {
int[] arr = {1,4,12,35,14,11};
//int key = 2;
int key = 4;
// int a = BinarySearchRecursive(arr,key,0,arr.length - 1);
int a = BinarySearch(arr, key);
if(a == -1){
System.out.println("查找的是"+key+",数组中没有该数!");
}else{
System.out.println("查找的是"+key+",找到在数组中的位置坐标为:"+a);
}
}
}
交替打印奇偶数
GO:
func main() {
ch := make(chan int)
go grount2(ch,100)
go grount1(ch,100)
time.Sleep(time.Second * 1)
}
func grount1(p1 chan int, count int) {
for i := 0; i <= count; i++ {
p1 <- i
if i%2 == 0 {
fmt.Println("grount1:", i)
}
}
}
func grount2(p1 chan int,count int) {
for i := 0; i <= count; i++ {
<-p1
if i%2 != 0 {
fmt.Println("grount2:", i)
}
}
}
JAVA:
package com.csq.study;
public class ChangeDemo {
private int count = 0;
private final Object lock = new Object();
public void turning() throws InterruptedException {
new Thread(new TurningRunner()).start();
Thread.sleep(1);
new Thread(new TurningRunner()).start();
}
public class TurningRunner implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(count);
count++;
lock.notifyAll();
try {
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
final ChangeDemo changeDemo = new ChangeDemo();
changeDemo.turning();
}
}
ok ,个人觉得go对于线程的操作还是比java要简单很多
未完待续 ......