Java算法之排序(快速,冒泡,归并,选择)

来源:互联网 发布:淘宝证书安装 编辑:程序博客网 时间:2024/06/05 08:54

下面是个人整理的几种排序算法,不算太难,有一定基础的认真看看都可理解。归并算法思想比较简单,但在写代码时要注意处理好边界问题,注意对数组的赋值和改变。

(选择排序)

//选择排序public class N1_1 {private int a[];public N1_1(){}public N1_1(int[] a){this.a = a;}public int[] result(){for(int i = 0; i < a.length; i++){int min = a[i];int temp;int index = i;for(int j = i + 1; j < a.length; j++ ){if(min > a[j]){min = a[j];index = j;}}temp = a[i];a[i] = min;a[index] = temp;}return a;}public static void main(String[] args) {// TODO Auto-generated method stubint a[] = {5,3,6,2,7,8,3,3,3};N1_1 n = new N1_1(a);a = n.result();for(int i = 0; i < a.length; i++){System.out.println(a[i]);}}}


(冒泡排序)

public class N1_2 {private int a[];public N1_2(){}public N1_2(int[] a){this.a = a;}public int[] result(){int temp;for(int i = 0; i < a.length; i++){for(int j = 0; j < a.length - 1; j++){if(a[j] > a[j+1]){temp = a[j];a[j] = a[j+1];a[j+1] = temp;}}}return a;}public static void main(String[] args) {// TODO Auto-generated method stubint a[] = {1,2,4,3,3,5,5,3,4,5};N1_2 n = new N1_2(a);a = n.result();for(int i = 0; i < a.length; i++){System.out.println(a[i]);}}}
(快速排序)

//快速排序public class N6_4 {public static int[] quicksort(int[] v,int left,int right){if(left<right){int key = v[left];int low = left;int high = right;while(low < high){while(low < high && v[high] >= key){high--;}v[low] = v[high];while(low < high && v[low] <= key){low++;}v[high] = v[low];}v[low] = key;quicksort(v,left,low-1);quicksort(v,low+1,right);}return v;}public static void main(String[] args) {// TODO Auto-generated method stubint[] a = {1,4,5,3,8,2,6,9,7};int[] v = quicksort(a,0,8);System.out.println(Arrays.toString(v));}}
(归并排序)

public class GuiBing {    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];          }      }public static int[] mergeSort(int[] str, int p, int r){int q = (p+r)/2;if(p < r){mergeSort(str,p,q);mergeSort(str,q+1,r);merge(str,p,q,r);}return str;}public static void main(String[] args) {// TODO Auto-generated method stubint[] a = {3,4,2,6,8,7,6,9};mergeSort(a,0,7);System.out.println(Arrays.toString(mergeSort(a,0,7)));}}




阅读全文
1 0