选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中 继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
下面是java实现选择排序的代码片段:
- public void selectionSort(int data[],int n)
- // pre: 0<=n <= data.length
- // post: values in data[0..n-1] in ascending order
- {
- int numUnsorted=n; // number of values not in order
- int index; // general index
- int max;
- int temp;
- while (numUnsorted > 0)
- {
- //determine a maximum value in Array
- max=0;
- for (index=1; index < numUnsorted; index++)
- if (data[max] < data[index])
- max=index;
- // swap data[max] and data[numUnsorted-1]
- temp = data[max];
- data[max] = data[numUnsorted-1];
- data[numUnsorted-1] = temp;
- numUnsorted--;
- }
- }
来源: http://www.phpxs.com/code/1002612/