How can I sort odd numbers to come first followed by even numbers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

How can I sort odd numbers to come first followed by even numbers

I want to sort in that, this input:[5,1,3,9,2,6,4,7,8] would result to:[1,3,5,7,9,2,4,6, 8] ::odds sorted, then followed by the evens. I code in python and Javascript, so I would prefer theuse of those two languages, but you can also give an answer in any other language.

20th Jul 2017, 11:17 PM
Krafty Coder
Krafty Coder - avatar
4 Answers
20th Jul 2017, 11:58 PM
Maz
Maz - avatar
21st Jul 2017, 1:44 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 5
I'm not a python programmer, but you can try a bubble sort, with different criteria this time around (i.e. if |number[n]| % 2 > |number[n + 1]| % 2 then swap them)
21st Jul 2017, 5:07 AM
Garikai
Garikai - avatar
0
Python is my next goal... for now, with Ruby, I can suggest this (I am sure a Python or JavaScript solution would be quite similar): nums = [5,1,3,9,2,6,4,7,8] even_nums = nums.select { |x| (x % 2) == 0 } odd_nums = nums.select { |x| (x % 2) != 0 } sorted_nums = odd_nums.sort + even_nums.sort print sorted_nums (using modulo 2 to identify odds and evens, selecting on that criteria, recombining after sorting)
20th Jul 2017, 11:32 PM
André
André - avatar