本文主要是介绍快速排序和归并排序模板(Java实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
快速排序
public static void quick_sort(int[] q, int l, int r) {if (l >= r) return;int i = l - 1, j = r + 1, x = q[l + r >> 1];while (i < j) {do i ++; while (q[i] < x);do j --; while (q[j] > x);if (i < j) {int t = q[i];q[i] = q[j];q[j] = t;}}quick_sort(q, l, j);quick_sort(q, j + 1, r);
}
归并排序
public static void merge_sort(int[] q, int l, int r) {if (l >= r) return;int mid = l + r >> 1;merge_sort(q, l, mid);merge_sort(q, mid + 1, r);int k = 0, i = l, j = mid + 1;int[] tmp = new int[q.length];while (i <= mid && j <= r)if (q[i] < q[j]) tmp[k ++] = q[i ++];else tmp[k ++] = q[j ++];while (i <= mid) tmp[k ++] = q[i ++];while (j <= r) tmp[k ++] = q[j ++];for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j];
}
测试代码
public static void main(String[] args) {final int size = 10;int[] a = new int[size];// 快速排序for (int i = 0; i < size; i ++) {a[i] = (int) (Math.random() * 100);}quick_sort(a, 0, a.length - 1);for (int i : a) {System.out.print(i + " ");}System.out.println();//归并排序for (int i = 0; i < size; i ++) {a[i] = (int) (Math.random() * 100);}merge_sort(a, 0, a.length - 1);for (int i : a) {System.out.print(i + " ");}
}
这篇关于快速排序和归并排序模板(Java实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!