龙空技术网

快排,归并,二分代码模板

千楼 145

前言:

眼前姐妹们对“二分归并算法伪代码”都比较讲究,同学们都需要了解一些“二分归并算法伪代码”的相关知识。那么小编也在网上收集了一些关于“二分归并算法伪代码””的相关资讯,希望咱们能喜欢,兄弟们快快来了解一下吧!

快速排序:

public static void quickSort(int[] arr, int left, int right) {    if (left >= right) return;    int x = arr[left], i = left - 1, j = right + 1;    while (i < j) {        do i++; while (arr[i] < x);        do j--; while (arr[j] > x);        if (i < j) swap(arr, i, j);    }    quickSort(arr, left, j);    quickSort(arr, j + 1, right);}private static void swap(int[] arr, int i, int j) {    int t = arr[i];    arr[i] = arr[j];    arr[j] = t;}

归并排序:

public static void mergeSort(int[] arr, int left, int right) {    if (left >= right) return;    int mid = left + right >> 1;    mergeSort(arr, left, mid);    mergeSort(arr, mid + 1, right);    int len = right - left + 1;    int[] temp = new int[len];    int i = left, j = mid + 1, k = 0;    while (i <= mid && j <= right) {        if (arr[i] < arr[j]) {            temp[k++] = arr[i++];        } else {            temp[k++] = arr[j++];        }    }    while (i <= mid) {        temp[k++] = arr[i++];    }    while (j <= right) {        temp[k++] = arr[j++];    }    for (i = 0, j = left; j <= right; i++, j++) {        arr[j] = temp[i];    }}

二分查找:

public static int two(int[] arr, int x) {    int l = 0, r = arr.length - 1, m = 0;    while (l <= r) {        m = l + r >> 1;        if (arr[m] == x) {            break;        }        if (arr[m] < x) {            l = m + 1;        } else {            r = m - 1;        }    }    return l > r ? -1 : m;}

标签: #二分归并算法伪代码