首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

一路面试题-一任意整数数组。写一个函数,把数组里的奇数放前面。偶数放后面

2012-10-25 
一道面试题-一任意整数数组。写一个函数,把数组里的奇数放前面。偶数放后面。一坨任意整数数组。写一个函数,把

一道面试题-一任意整数数组。写一个函数,把数组里的奇数放前面。偶数放后面。
一坨任意整数数组。写一个函数,把数组里的奇数放前面。偶数放后面。来自http://blog.csdn.net/g9yuayon/article/details/2679202
想到了算法之一

# this function is used to move all odd number to front part of an array and even numbers end.def test(arr) endix = arr.size-1 arr.each_with_index do |v,i|         if i >= endixreturn end  if v % 2 == 0 # met a even # swap this even with the last odd until arr[endix] % 2 == 1 or endix <= iendix -= 1 end arr[i],arr[endix]=arr[endix],arr[i] end endend

时间复杂度是O(n),空间复杂度是O(1).

热点排行