Given an array of positive and negative integers, re-arrange it so that you have positive integers on one end and negative integers on other

后端 未结 30 2598
醉梦人生
醉梦人生 2020-12-07 07:37

I recently came across a Microsoft Interview Question for Software Engineer.

Given an array of positive and negative integers, re-arrange it so that you

30条回答
  •  难免孤独
    2020-12-07 08:30

    This uses partition process of QuickSort. The time complexity of this solution is O(n2) and auxiliary space is O(1). This approach maintains the order of appearance and have not used any other data structure. This is in Ruby

    def sortSeg(intArr)
        intArr.each_with_index do |el, idx|
            # if current element is pos do nothing if negative,
            # shift positive elements of arr[0..i-1],
            # to one position to their right */
            if el < 0
                jdx = idx - 1;
                while (jdx >= 0 and intArr[jdx] > 0)
                    intArr[jdx + 1] = intArr[jdx];
                    jdx = jdx - 1;
                end
                # Insert negative element at its right position
                intArr[jdx + 1] = el;
            end
        end
    end
    

提交回复
热议问题