冒泡排序
for(int i =0;i<arr.length-1;i++) {
for(int j=0;j<arr.length-i-1;j++) {//-1为了防止溢出
if(arr[j]>arr[j+1]) {
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
二分查找法
给定数组是按从小到大排序好的
//先排序
bubbleSort(arr);
int left = 0;
int right = arr.length - 1;
int mid;
while(left <= right){
mid = (left + right) % 2 == 0 ? (left + right) / 2 : (left + right) / 2 + 1;
if(arr[mid] > val){
right = mid ;
}else if (arr[mid] < val){
left = mid ;
}else{
//找到该值
** System.out.println(mid);**
return;
}
}
}
单链表反转
public class SingleLinkedList{
private static class Node{
private int val;
private Node next;
}
//递归反转1-2-3-4
public Node reverse1(Node node){
if(node.next ==null || node== null){
return node;
}
Node temp= node.next;
Node newNode = reverse1(node.next);
node.next = null;
temp.next = node;
return newNode;
}
//遍历1-2-3-4
public Node reverse2(Node head){
Node prev = null;
Node next = null;
while (head != null){
next = head.next;
head.next = prev; //在这里完成4->3->2->1
prev = head;
head = next;
}
return prev;
}
}