Insertion Sort in Java, C,C++ and Python

本文深入探讨了插入排序算法的实现原理,提供了Java、C和Python三种语言的代码示例,展示了如何通过插入排序对整数数组进行排序的过程。

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

/**
 * @Author: Chintsai Hwo
 * @Date: Created on 5:40 AM 6/2/2019
 */

import java.util.Scanner;

public class InsertSort {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Input the size of the int array: ");
        int arraySize = scanner.nextInt();
        int[] intArray = new int[arraySize];
        System.out.println("Input the elements of the int array: ");
        for (int i = 0; i < intArray.length; i++) {
            intArray[i] = scanner.nextInt();
        }
        insertionSort(intArray);
    }

    static void insertionSort(int[] a) {
        int i, j;
        int k;
        for (j = 1; j < a.length; j++) {
            k = a[j];
            i = j - 1;
            while (i >= 0 && a[i] > k) {
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = k;
        }
        System.out.println("The sorting result is: ");
        for (int arrayElement : a)
            System.out.print(arrayElement + " ");
    }
}
#include <stdio.h>

void insertionSort(int array[]);

int main() {
    int a[] = {5, 27, 5, 43, 4, 3, 2, 12};
    insertionSort(a);
    return 0;
}

void insertionSort(int array[]) {
    int length = sizeof(array);
    int i, j;
    int k;
    for (j = 1; j < length; j++) {
        k = array[j];
        i = j - 1;
        while (i >= 0 && array[i] > k) {
            array[i + 1] = array[i];
            i--;
        }
        array[i + 1] = k;
    }
    for (int index = 0; index < length; index++)
        printf("%d ", array[index]);
    return;
}
#include <iostream>

using namespace std;

void insertionSort(int a[]);

int main() {
    int a[] = {4, 2, 63, 25, 6, 75, 1, 3};
    insertionSort(a);
    for (int index = 0; index < sizeof(a) / sizeof(int); index++)
        cout << a[index] << " ";
    return 0;
}

void insertionSort(int a[]) {
    int i, j;
    int k;
    int length = sizeof(a);
    for (j = 1; j < length; j++) {
        k = a[j];
        i = j - 1;
        while (i >= 0 && a[i] > k) {
            a[i + 1] = a[i];
            i--;
        }
        a[i + 1] = k;
    }
}
def insertion_sort(array):
    for j in range(1, len(array)):
        k = array[j]
        i = j - 1
        while i >= 0 and array[i] > k:
            array[i + 1] = array[i]
            i = i - 1
        array[i + 1] = k
    print(array)


a = [32, 14, 1, 2, 4, 3, 23]
if __name__ == "__main__":
    insertion_sort(a)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

「已注销」

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

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

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

打赏作者

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

抵扣说明:

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

余额充值