zoukankan      html  css  js  c++  java
  • 插入排序

    插入排序的关键思想是每次将后端未排序序列的第一个元素插入到前面已经有序的序列中,并且在插入过程中需要与比当前“大”的元素交换位置。插入排序总的交换次数等于原始输入序列的逆序数。简易实现及测试用例如下:

    import java.util.logging.Handler;
    
    public class Insertion {
    
        private static void exch(Comparable[] a, int i, int j) {
            Comparable tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
    
        private static boolean less(Comparable a, Comparable b) {
            return (a.compareTo(b) < 0);
        }
    
        private static void show(Comparable[] a) {
            int N = a.length;
            for (int i = 0; i < N; i++) {
                System.out.print(a[i] + " ");
            }
            System.out.println();
        }
    
        public static boolean isSorted(Comparable[] a) {
            int N = a.length;
            for (int i = 1; i < N; i++) {
                if (less(a[i], a[i - 1]))
                    return false;
            }
            return true;
        }
    
        public static void sort(Comparable[] a) {
            int N = a.length;
            for (int i = 0; i < N; i++) {
                for (int j = i; j > 0 && less(a[j], a[j - 1]); j--) {
                    exch(a, j, j - 1);
                }
            }
        }
    
        public static void main(String[] args) {
            String[] a = StdIn.readAllStrings();
            Selection.sort(a);
            show(a);
        }
    
    }
    View Code
  • 相关阅读:
    JSP 学习笔记1
    XML scriptlet 连接数据库
    JSP 定义行列数表单创建表格
    JSP_01
    JS创建表格完整
    04-基本的mysql语句
    03-MySql安装和基本管理
    02-数据库概述
    01-MySql的前戏
    爬虫系列
  • 原文地址:https://www.cnblogs.com/wwblog/p/3982038.html
Copyright © 2011-2022 走看看