54.调整数组顺序使奇数位于偶数前面。

本文介绍了一个VB.NET程序,该程序可以接收一个整数数组作为输入,并将数组中的奇数和偶数分别放置在数组的前半部分和后半部分。此算法的时间复杂度为O(n),通过双指针技术实现,一个从头部开始向后遍历,另一个从尾部开始向前遍历。

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

题目:输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,
所有偶数位于数组的后半部分。要求时间复杂度为O(n)。

 

VB.NET codes as below:

 

Module MyModule

 

    Sub Main()

        Dim array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 9, 8, 7, 6, 5, 4, 3, 2, 2}

 

        array = SortArray(array)

 

        For Each i As Integer In array

            Console.WriteLine(i)

        Next

 

        Console.ReadKey()

    End Sub

 

    Public Function SortArray(ByVal array As Integer()) As Integer()

        If Not array Is Nothing Then

            Dim startIndex = 0

            Dim endIndex = array.Length - 1

 

            While (startIndex < endIndex)

                If Not (array(startIndex) Mod 2 = 0) Then

                    startIndex += 1

                ElseIf (array(endIndex) Mod 2 = 0) Then

                    endIndex -= 1

                Else

                    Dim mark = array(startIndex)

                    array(startIndex) = array(endIndex)

                    array(endIndex) = mark

                    startIndex += 1

                    endIndex -= 1

                End If

            End While

        End If

        Return array

    End Function

End Module

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值