简单选择排序算法

package BrushProblem.sortQuestion;

public class SimpleSelectSort {

public static void main(String[] args) {
int[] array = {23, 12, 4, 56, 0, 1};
simpleSelectSort(array);
array = new int[]{23, 12, 4, 56, 0, 1};
simpleSelectSort2(array);
}

/*
思路:https://www.cnblogs.com/lijingran/p/8695121.html
* 简单选择排序
* 思路:在待排序数据中,选出最小的一个数与第一个位置的数交换;然后在剩下的数中选出最小的数与第二个数交换;依次类推,直至循环到只剩下两个数进行比较为止。
* */
public static void simpleSelectSort(int[] array) {
if (array != null && array.length > 1) {

for (int i = 0; i < array.length; i++) {
int temp = 0;
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
//先只找最小的index,不交换
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (i != minIndex) {
temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
System.out.println("简单选择排序");
print(array, i);
}
System.out.println("完毕!");
}
}

/*
简单选择排序改进算法
思路:简单选择排序算法,每次只选择一个数据放在正确的位置,为提高效率,可每次选择两个数据,放在正确的位置,及每次选择最大值和最小值。
* */
public static void simpleSelectSort2(int[] array) {
if (array != null && array.length > 1) {
int length = array.length;
for (int i = 0; i < length / 2; i++) {
int minIndex = i;
int maxIndex = i;//注意的地方
for (int j = i + 1; j < length - i; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
if (array[maxIndex] < array[j]) {
maxIndex = j;
}
}
if (minIndex != i) {
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
if (maxIndex != i) {
int temp = array[maxIndex];
array[maxIndex] = array[length - 1 - i];//注意的地方
array[length - 1 - i] = temp;//注意的地方
}
System.out.println("简单选择排序--改良");
print(array, i);
}
System.out.println("完毕!");
}
}

/**
* 打印排序的每次循环的结果
*
* @param a
* @param i
*/
private static void print(int[] a, int i) {
// TODO Auto-generated method stub
System.out.print("第" + i + "次:");
for (int j = 0; j < a.length; j++) {
System.out.print(" " + a[j]);
}
System.out.println();
}
}

转载于:https://www.cnblogs.com/lijingran/p/8695121.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值