算法(第四版)——02选择排序

来源:互联网 发布:淘宝客网站要多大空间 编辑:程序博客网 时间:2024/05/16 14:15

选择排序:1,找到数组中最小的那个元素,2,将它和数组的第一个元素交换位置(如果第一个元素最小,那么就和自己交换)。3,在剩下的元素中找到最小的元素,将它与第二个元素交换位置。如此往复,直到整个数组排序完成。

下面以对一个整型数组排序为例进行代码实现:

public class Selection {public static void selectionSort(int[] a){int N = a.length;for (int i = 0; i < N; i++) {int min = i; for (int j = i+1; j < N; j++) {if(a[j]<a[min]) {min = j;}}int temp = 0;temp = a[min];a[min] = a[i];a[i] = temp;}}public static void main(String[] args) {int[] a = {13,67,22,45,12,89,76,42,67};System.out.println("原始顺序是:");for (int i : a) {System.out.print(i + " ");}System.out.println();selectionSort(a);System.out.println("排序后的顺序是:");for (int i : a) {System.out.print(i + " ");}}}

运行结果为:

原始顺序是:
13 67 22 45 12 89 76 42 67 
排序后的顺序是:
12 13 22 42 45 67 67 76 89 


算法第四版的选择排序代码如下:

public class Selection {@SuppressWarnings("rawtypes")public static void sort(Comparable[] a) {int N = a.length;for (int i = 0; i < N; i++) {int min = i;for (int j = i+1; j < N; j++) {if(less(a[j],a[min]))//是否a[j]<a[min],成立的话的则min=jmin = j;}exch(a,i,min);}}@SuppressWarnings("rawtypes")private static void exch(Comparable[] a, int i, int j) {Comparable t = a[i];a[i] = a[j];a[j] = t;}@SuppressWarnings({ "rawtypes", "unchecked" })private static boolean less(Comparable v, Comparable w) {return v.compareTo(w)<0;}@SuppressWarnings("rawtypes")private static void show(Comparable[] a){for (int i = 0; i < a.length; i++) {System.out.print(a[i] + " ");if((i+1)%5==0)System.out.println();}System.out.println();}}
在其中添加主方法即可运行。

0 0