各种排序算法汇总(JAVA版,不定期更新)

来源:互联网 发布:java微信商城源码 编辑:程序博客网 时间:2024/05/18 01:22

参考网址:

http://blog.csdn.net/pzhtpf/article/details/7560294

1. 快速排序

package com.zby.quicksort;public class QuickSort {int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99,98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 };public QuickSort() {quick(a);for (int i = 0; i < a.length; i++)System.out.println(a[i]);}public int getMiddle(int[] list, int low, int high) {int tmp = list[low]; // 数组的第一个作为中轴while (low < high) {while (low < high && list[high] >= tmp) {high--;}list[low] = list[high]; // 比中轴小的记录移到低端while (low < high && list[low] <= tmp) {low++;}list[high] = list[low]; // 比中轴大的记录移到高端}list[low] = tmp; // 中轴记录到尾return low; // 返回中轴的位置}public void _quickSort(int[] list, int low, int high) {if (low < high) {int middle = getMiddle(list, low, high); // 将list数组进行一分为二_quickSort(list, low, middle - 1); // 对低字表进行递归排序_quickSort(list, middle + 1, high); // 对高字表进行递归排序}}public void quick(int[] a2) {if (a2.length > 0) { // 查看数组是否为空_quickSort(a2, 0, a2.length - 1);}}public static void main(String[] args) {QuickSort qs = new QuickSort();}}

2. 冒泡排序

package com.zby.bubblesort;public class BubbleSort {public BubbleSort(){int[] a = {49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; int temp = 0;for(int i = 0; i < a.length; i++)for(int j = 0; j < a.length - i - 1; j++){if(a[j] > a[j+1]){temp = a[j];a[j] = a[j+1];a[j+1]=temp;}}for( int i = 0; i < a.length; i++)System.out.println(a[i]);}public static void main(String[] args) {BubbleSort bs = new BubbleSort();}}

3. 二分查找

package com.zby.jianzhioffer;public class BinarySearch {public static int binarySearch(int[] arr, int goal) {int start = 0;int end = arr.length - 1;while (start <= end) {int middle = (start + end)/2;if(arr[middle] == goal)return middle + 1;else if(arr[middle] > goal)end = middle - 1;else if(arr[middle] < goal)start = middle + 1;}return -1;}public static void main(String[] args) {int[] a = {1,2,4,7,9,10,14,45,68,69,78,88,92,100,144,156,167};System.out.println(binarySearch(a, 78));}}

4. 归并排序

参考链接:

http://blog.csdn.net/middlekingt/article/details/8446552

package com.zby.jianzhioffer;public class MergeSort {public static int[] sort(int[] nums, int low, int high) {int mid = (low + high) / 2;if(low < high) {//左边sort(nums, low, mid);//右边sort(nums, mid + 1, high);//左右归并merge(nums, low, mid, high);}return nums;}public static void merge(int[] nums, int low, int mid, int high) {int[] temp = new int[high - low + 1];int i = low;//左指针int j = mid + 1;//右指针int k = 0;//除了最后的一个大数,把所有的数转移到新数组中while(i <= mid && j <= high) {if(nums[i] < nums[j]) {temp[k++] = nums[i++];}else {temp[k++] = nums[j++];}}//把左边剩余的数移入数组while(i <= mid) {temp[k++] = nums[i++];}//把右边剩余的数移入数组while(j <= high) {temp[k++] = nums[j++];}//把新数组中的数覆盖nums数组for(int k2 = 0; k2 < temp.length; k2++) {nums[k2 + low] = temp[k2];}}}


0 0
原创粉丝点击