java通关整理汇总-Java基础、计算机网络、数据库、框架、设计模式、算法模板、笔试
1.冒泡排序
每一次比较相邻的两个数,每一轮把最大的一个数移到最后
public static int[] doubleSort(int[] s){
int temp;
boolean flag = false;
for (int i = 0; i < s.length; i++) {
flag = true;
for (int j = 0; j < s.length-i-1; j++) {
if(s[j]>s[j+1]){
//交换相邻两个数字
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
flag = false;
}
}
if(flag){
break;
}
}
return s;
}
2.快速排序
先找第一个数做基准temp,从右向左找到第一个小于temp的数,从左向右找到第一个大于temp的数,然后两个数交换,知道两个指针相遇,再把基准temp和两个指针相遇的位置交换。
递归方法:
/**
* 快速排序演示
* @author Lvan
*/
public class QuickSort {
public static void main(String[] args) {
int[] arr = {5, 1, 7, 3, 1, 6, 9, 4};
quickSort(arr, 0, arr.length - 1);
for (int i : arr) {
System.out.print(i + "\t");
}
}
/**
* @param arr 待排序列
* @param leftIndex 待排序列起始位置
* @param rightIndex 待排序列结束位置
*/
private static void quickSort(int[] arr, int leftIndex, int rightIndex) {
if (leftIndex >= rightIndex) {
return;
}
int left = leftIndex;
int right = rightIndex;
//待排序的第一个元素作为基准值
int key = arr[left];
//从左右两边交替扫描,直到left = right
while (left < right) {
while (right > left && arr[right] >= key) {
//从右往左扫描,找到第一个比基准值小的元素
right--;
}
//找到这种元素将arr[right]放入arr[left]中
arr[left] = arr[right];
while (left < right && arr[left] <= key) {
//从左往右扫描,找到第一个比基准值大的元素
left++;
}
//找到这种元素将arr[left]放入arr[right]中
arr[right] = arr[left];
}
//基准值归位
arr[left] = key;
//对基准值左边的元素进行递归排序
quickSort(arr, leftIndex, left - 1);
//对基准值右边的元素进行递归排序。
quickSort(arr, right + 1, rightIndex);
}
}
非递归:
// start和end为前闭后闭
private static void nonRec_quickSort(int[] a, int start, int end) {
// 用栈模拟
Stack<Integer> stack = new Stack<>();
if (start < end) {
stack.push(end);
stack.push(start);
while (!stack.isEmpty()) {
int l = stack.pop();
int r = stack.pop();
int index = partition(a, l, r);
if (l < index - 1) {
stack.push(index - 1);
stack.push(l);
}
if (r > index + 1) {
stack.push(r);
stack.push(index + 1);
}
}
}
System.out.println(Arrays.toString(a));
}
private static int partition(int[] a, int start, int end) {
int pivot = a[start];
while (start < end) {
while (start < end && a[end] >= pivot)
end--;
a[start] = a[end];
while (start < end && a[start] <= pivot)
start++;
a[end] = a[start];
}
a[start] = pivot;
return start;
}