0
while (i<r && j<u) { 
    if (a[i]<=a[j]) {
      b[k]=a[i]; 
      i++;
    } 
    else {
      b[k]=a[j];
      j++;
    }
    k++;
}

In the above C++ code values of two arrays is checked and value of one array is assigned to another array when the depending upon the condition satisfies.

am beginner programmer in python.There is something called list in python similar to array in c++. how the above code can be implemented in python?

3
  • Out of interest, what is this code doing? This algorithm looks vaguely familiar... Commented Jun 21, 2013 at 10:25
  • am trying to implement merge sort in iterative version Commented Jun 21, 2013 at 10:50
  • then the pythonic way is to do list(sorted(a)). but if you insist on implementing merge, use can drop the k variable and use b.append(min(a[i], a[j])) instead. Commented Jun 21, 2013 at 11:05

1 Answer 1

1

There is a list construct baked right into the core of Python, below is a pretty good introduction:

http://www.tutorialspoint.com/python/python_lists.htm

You could re-write the code above pretty much identically in python, just changing the syntax from C++ to python. However, there may be a more pythonic way of doing what you require, it is hard to say without having more context around the code.

while i < r and j < u:
    if a[i] <= a[j]:
        b[k] = a[i]
        i += 1               # No increment operator in python
    else:
        b[k] = a[j]
        j += 1
    k += 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.