zoukankan      html  css  js  c++  java
  • 简单选择排序算法

    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();
    }
    }
  • 相关阅读:
    tuple 元组及字典dict
    day 49 css属性补充浮动 属性定位 抽屉作业
    day48 选择器(基本、层级 、属性) css属性
    day47 列表 表单 css初识
    day 46 http和html
    day 45索引
    day 44 练习题讲解 多表查询
    day 40 多表查询 子查询
    day39 表之间的关联关系、 补充 表操作总结 where 、group by、
    day38 数据类型 约束条件
  • 原文地址:https://www.cnblogs.com/lijingran/p/8695121.html
Copyright © 2011-2022 走看看