选择排序
原理简介:依次从当前位置遍历到最后,查找出最小数,然后将其与当前位置调换。
python 代码:
from random import randint
def selection_sort():
#generate a unsorted list
origin = []
for i in xrange(0,10,1):
origin.append(randint(1,10))
#selection sort
print origin
#loop n-1
end = len(origin) -1
for i in xrange(0,end,1):
key = origin[i]
j=i+1
index = i
for j in xrange(i+1,end+1,1):
if origin[j] < key:
key = origin[j]
index = j
origin[index] = origin[i]
origin[i] = key
print origin
if __name__ == "__main__":
selection_sort()
java 代码:
package blog.algorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SelectionSort {
public static void main(String args[]){
System.out.println("begin...");
List<Integer> origin = new ArrayList<Integer>();
int count = 10;
Random rd = new Random();
while(count > 0){
int i = rd.nextInt(100);
origin.add(i);
count--;
System.out.print("" + i + " ");
}
System.out.println();
int key;
for(int i = 0,len = origin.size()-1; i < len; i++){
key = origin.get(i);
int index = i;
for(int j = i+1;j <= len;j++){
if(origin.get(j) < key){
key = origin.get(j);
index = j;
}
}
origin.set(index, origin.get(i));
origin.set(i, key);
}
for(int i = 0,len = origin.size(); i < len; i++){
System.out.print("" + origin.get(i) + " ");
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。