首页 > 学院 > 开发设计 > 正文

【排序算法】之选择排序

2019-11-08 03:02:47
字体:
来源:转载
供稿:网友

基本思想:在要排序的一组数中,选出最小的一个数与第一个位置的数交换;然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。

这里写图片描述

public class Main { public static void main(String[] args) { System.out.PRintln("Hello World!"); int[] numbers = {57,68,59,52};//排序前 selectionSort(numbers); } /** * 选择排序算法 * 在未排序序列中找到最小元素,存放到排序序列的起始位置 * 再从剩余未排序元素中继续寻找最小元素,然后放到排序序列末尾。 * 以此类推,直到所有元素均排序完毕。 * @param numbers */ public static void selectionSort(int[] numbers){ int size = numbers.length; int temp = 0 ; for (int i=0; i< size; i++){ int k = i;//待确定的位置 for(int j = size -1; j>i; j--){//从后往前搜索 if(numbers[j] < numbers[k]){ k = j;//将较小值 index 赋值给k } } //交换两个数 temp = numbers[i]; numbers[i] = numbers[k]; numbers[k] = temp; } System.out.println("排序后:"); for (int num: numbers) System.out.print(num + "/t"); }}Terminal输出:Hello World!排序后:52 57 59 68
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表