Geek Culture
Published in

Geek Culture

Sort an Array in Ascending order but zero should be at the end in Swift

Hi Guys hope you under stand how to solve this problem by using the Swift Language.

Our input and output arrays will be like this

Input = [10,0,2,3,0,1,3,0], OutPut= [1,2,3,3,10,0,0,0]

Step-1

Create a function which will take the array as an input and will return the array as an output.

By default the function parameters in swift are not mutable so making them mutable we can use the inout keyword with data type of the parameters.

Create a count variable which will use as a counter. Now all elements which are greater than zero shifted at first indexes and also update the counter as well when any element shift upward.

Step-2

Now make all remaining array indexes which are grater than count to zero

Step-3

Now sort the array till count and then you will get your desired result.

Input = [10,0,2,3,0,1,3,0], OutPut= [1,2,3,3,10,0,0,0]

Complete Code:

Hope you like this blog. Thanks for reading this. 😊

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store