java选择算法

来源:互联网 发布:苹果8移动网络连接不上 编辑:程序博客网 时间:2024/05/22 03:38

1.算法主程序

package array;public class SelectSort {private long[] a;private int nElemes;// the numbers of array// ---------constructed function----------public SelectSort(int max) {a = new long[max];nElemes = 0;}// ----------size()-------public int size() {return nElemes;}// --------insert----------public void insert(long value) {a[nElemes] = value;nElemes++;}// -----------select---选择排序主算法---------public void select() {while (size() > 0) {//当元素个数为一时,默认是有序的int min, outer, inner;for (outer = 0; outer < size()-1; outer++) {//out for loopmin = outer;for (inner = outer+1; inner < size(); inner++)//inner for loopif (a[inner] < a[min])min = inner;swap(outer, min);}break;}}// end bubbleSort// --------display()--------public void display() {for (int i = 0; i < size(); i++)System.out.print(a[i] + "  ");System.out.println();}// ----swap---交换两个元素的值---public void swap(int i, int j) {long k;k = a[i];a[i] = a[j];a[j] = k;}}


 

2.算法验证

package array;public class SelectApp {/** * @param args */public static void main(String[] args) {SelectSort sort = new SelectSort(10);sort.insert(56);sort.insert(52);sort.insert(41);sort.insert(40);sort.insert(2);System.out.println("排序前:");sort.display();System.out.println("排序后:");sort.select();sort.display();}}


 

3.验证结果

排序前:56  52  41  40  2  排序后:2  40  41  52  56  


 

原创粉丝点击