排序算法(2)插入排序的编程语言实现

本文提供插入排序的C++及Java实现代码,并展示每轮排序结果,适用于初学者理解算法原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导语

我们在上文中分析了插入排序的算法以及及其时间复杂度分析,分析最好情况和最坏情况下的时间复杂度。本文则就对上文的算法进行实现。
如果没有看过分析的,请去查看
排序算法(1)插入排序的算法分析

伪代码1

INSERTION-SORT(A)
   for j=2 to A.length
       key = A[j]
       //Insert A[j] into the sorted sequence A[1..j-1]
       i = j - 1
       while i > 0 and A[i] > key
           A[i+1] = A[i]
           i = i - 1
       A[i+1]=key

伪代码2

INSERTION-SORT(A)
   for j=2 to A.length
       //Insert A[j] into the sorted sequence A[1..j-1]
       i = j
       while i > 0 and A[i] < A[i-1]//当前面的比它大,和它换位
           exchange(A,i,i-1)
           i = i - 1

C plus plus语言实现插入排序

源码实现1

#include <iostream>
using namespace std;

/**
*插入排序的实现
*/
void PrintSortedArray(int a[], int n);
void InsertSort(int a[], int n)
{
    int i = 0;
    for (int j = 1; j < n; j++)
    {
        int key = a[j];
        //Insert A[j] into the sorted sequence A[1..j-1]
        i = j - 1;
        while (i >= 0 && a[i] > key)
        {
            a[i + 1] = a[i];
            i = i - 1;
        }
        a[i + 1] = key;
        cout << "第" << j << "次排序后:<";
        PrintSortedArray(a,n);
        cout << ">"<<endl;
    }
}
void PrintSortedArray(int a[], int n)
{
    for (int j = 0; j < n; j++)
    {
        cout << a[j] << " ";
    }
}
int main()
{
    cout << "****************************************************"<<endl;
    cout << "************   InserSortExample    *****************"<<endl;
    cout << "************     YuYunTan          *****************"<<endl;
    cout << "************     2016年7月         *****************"<<endl;
    cout << "****************************************************"<<endl;
    int a[] = { 1, 4, 2, 3, 5, 8, 7, 6 };
    int len = sizeof(a) / sizeof(a[0]);
    cout << "原数组为:<";
    PrintSortedArray(a, len);
    cout << ">"<<endl;
    InsertSort(a, len);
    cout << "\n\n最后排序为:\n<";
    PrintSortedArray(a, len);
    cout << ">"<<endl;
    system("pause");
    return 0;
}

运行后的结果图

运行图

源码实现2

#include <iostream>
using namespace std;

/**
*插入排序的实现
*/
void exchange(int &i, int &j);
void PrintSortedArray(int a[], int n);
void InsertSort(int a[], int n)
{
    for (int i = 1; i < n; i++)
    {
        //Insert A[j] into the sorted sequence A[1..j-1]
        int j = i;
        while (j > 0 && a[j] < a[j - 1])
        {
            exchange(a[j], a[j - 1]); j--;
        }
        cout << "第" << i << "次排序后:<";
        PrintSortedArray(a,n);
        cout << ">"<<endl;
    }
}
void exchange(int &i, int &j)
{
    int temp = i;
    i = j;
    j = temp;
}
void PrintSortedArray(int a[], int n)
{
    for (int j = 0; j < n; j++)
    {
        cout << a[j] << " ";
    }
}
int main()
{
    cout << "****************************************************"<<endl;
    cout << "************   InserSortExample    *****************"<<endl;
    cout << "************     YuYunTan          *****************"<<endl;
    cout << "************     2016年7月         *****************"<<endl;
    cout << "****************************************************"<<endl;
    int a[] = { 1, 4, 2, 3, 5, 8, 7, 6 };
    int len = sizeof(a) / sizeof(a[0]);
    cout << "原数组为:<";
    PrintSortedArray(a, len);
    cout << ">"<<endl;
    InsertSort(a, len);
    cout << "\n\n最后排序为:\n<";
    PrintSortedArray(a, len);
    cout << ">"<<endl;
    system("pause");
    return 0;
}

运行图

这里写图片描述

Java实现插入排序

源码实现1

package com.tqw.realize.chapter2;
/**
 * 本例子为插入排序的例子
 * @author tqw
 *
 */

public class Insertion {

    public static void sort(int []a){
        //将a[]按升序排列
        int N = a.length;
        for(int j=1;j<N;j++){
            //将a[i]插入到a[i-1]、a[i-2]、a[i-3]...之中
            int key=a[j];
            int i=j-1;
            for(;i>=0 && more(a[i],key);i--)
                        a[i+1]=a[i];            
            a[i+1]=key;
            System.out.print("第"+j+"次排序为:<");
            show(a);
            System.out.println(">");
        }
    }

    public static boolean more(int i, int j) {
        // TODO Auto-generated method stub
        return i>j;
    }

    public static void show(int a[]){
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+" ");
        }
    }

    public static void main(String[] args) {
        System.out.println("********************************************");
        System.out.println("**********  InsertSortExample  *************");
        System.out.println("**********       YuYunTan      *************");
        System.out.println("**********      2016-07-26     *************");
        System.out.println("********************************************");
        int []a={2,3,19,1,4,7,6,5,9,8,10};
        System.out.print("原数组为:<");
        show(a);
        System.out.println(">");
        sort(a);
        System.out.println("\n排序后的数组为:");
        show(a);

    }
}

运行结果

这里写图片描述

源码实现2

package com.tqw.realize.chapter2;
/**
 * 本例子为插入排序的例子
 * @author tqw
 *
 */

public class Insertion {

    public static void sort(int []a){
        //将a[]按升序排列
        int N = a.length;
        for(int i=1;i<N;i++){
            //将a[i]插入到a[i-1]、a[i-2]、a[i-3]...之中
            for(int j=i;j>0 && less(a[j],a[j-1]);j--)
                        exch(a,j,j-1);          
            System.out.print("第"+i+"次排序为:<");
            show(a);
            System.out.println(">");
        }
    }

    public static void exch(int[] a, int j, int i) {
        // TODO Auto-generated method stub
        int temp=a[j];
        a[j]=a[i];
        a[i]=temp;
    }

    public static boolean less(int i, int j) {
        // TODO Auto-generated method stub
        return i<j;
    }

    public static void show(int a[]){
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+" ");
        }
    }

    public static void main(String[] args) {
        System.out.println("********************************************");
        System.out.println("**********  InsertSortExample  *************");
        System.out.println("**********       YuYunTan      *************");
        System.out.println("**********      2016-07-26     *************");
        System.out.println("********************************************");
        int []a={2,3,19,1,4,7,6,5,9,8,10};
        System.out.print("原数组为:<");
        show(a);
        System.out.println(">");
        sort(a);
        System.out.println("\n排序后的数组为:");
        show(a);

    }
}

运行结果

这里写图片描述

结语

插入排序是初级排序的一种,算法思想很简单,但是复杂度很高,对于元素小的时候,可以选择这种排序,但是对于比较大量的排序,这个还是不划算的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuYunTan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值