Pages

Tuesday, February 8, 2011

Sorting digits of a number

This is the first post
Recently I came along an interesting problem.

Q A function has input (int[] array) enter any number(array of digits of that number is entered) and the resulting number should convert to absolute number like 4578,6789,1234 etc. i.e in increasing order.Solve this in O(nlogn)?

Well I used merge sort for this as follows since merge sort has a complexity of O(n) as follows

namespace absolute_no
{
class Program
{
static int[] mergesort(int []array)
{
int x;
if (array.Length <= 1)
return array;
int[] left,right,result;
int middle = array.Length / 2;
left=new int[middle];
result = new int[array.Length];
right = new int[array.Length-middle];
for (x = 0; x {
left[x] = array[x];
}
int y=0;
for (x = middle; x {
right[y] = array[x];
y++;
}
left = mergesort(left);
right = mergesort(right);
result = merge(left, right);
return result;
}

static int[] merge(int [] left,int[] right)
{
int [] result=new int[left.Length+right.Length];
int x=0;
int y=0;
int i=0;
do
{
if (left[x] <= right[y])
{
result[i] = left[x];
i++;
x++;
}
else
{
result[i] = right[y];
i++;
y++;
}
} while (x < left.Length && y < right.Length);
while(x {
result[i]=left[x];
x++;
i++;
}
while(y {
result[i]=right[y];
y++;
i++;
}
return result;
}
static void Main(string[] args)
{
int []arr = { 1, 7, 5, 6 };
arr = mergesort(arr);
}
}
}

No comments:

Post a Comment