选择排序算法

来源:互联网 发布:西部世界解析 知乎 编辑:程序博客网 时间:2024/06/09 18:50
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String cout = bufferedReader.readLine();
String[] s = cout.split(" ");
int[] arry = new int[s.length];
for (int i = 0; i < s.length; i++) {
arry[i] = Integer.parseInt(s[i]);
}
selectSort(arry);
for (int i : arry) {
System.out.print(" " + i);
}
}


public static void selectSort(int[] a) {
int current, temp;
for (int i = 0; i < a.length; i++) {
current = i;
for (int j = current + 1; j < a.length; j++) {
if (a[current] > a[j]) {
current = j;
}
}
if (current != i) {
temp = a[current];
a[current] = a[i];
a[i] = temp;
}
}
}

}


核心思想:用当前的数据与后面所有的数据进行比较,如果满足条件(大于或者小于),则进行位置交换,然后当前数据下标加一。

0 0
原创粉丝点击