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
  • 相关阅读:
    MySQL数据库基础
    Django框架
    Python基础
    C#
    小功能
    数据结构与算法
    C语言
    Robot Framework高级
    Robot Framework初级
    C++基础
  • 原文地址:https://www.cnblogs.com/wwblog/p/3982038.html
Copyright © 2011-2022 走看看