+ Reply to Thread
Results 1 to 2 of 2

Thread: Count number of negative integers

  1. #1
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321

    Count number of negative integers

    Count number of negative integers in left-to-right and top-to-bottom sorted 2D array (matrix).

  2. #2
    Surfer is offline Senior Member
    Join Date
    Mar 2010
    Posts
    321
    Assuming matrix is sorted left-right and top-to-bottom in increasing order.

    Code:
    
    int numNegatives(a[1..N][1...N])
    {
    	if (a[1][1] >= 0)
    		return 0;
    	if (a[N][N] < 0) 
    		return N*N;
    	row = 1;
    	col = N;
    	count = 0; //count is the number of negatives in the matrix
    	while (row <= N && col >= 1) {
    		if (a[row][col] < 0) {
    			count += col; //everything on the left of a(row,col)including itself are -ve
    			row++;
    		} else {
    			col--;
    		}
    	}
    	return count;
    }

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Count number of words in file
    By Surfer in forum Microsoft
    Replies: 0
    Last Post: 13th November 2010, 00:19
  2. Count number of nodes in a Binary Tree
    By Surfer in forum Microsoft
    Replies: 1
    Last Post: 8th October 2010, 04:53
  3. Count number of 1s
    By Surfer in forum Qualcomm
    Replies: 1
    Last Post: 21st May 2010, 13:33
  4. Count negative numbers in a matrix
    By Surfer in forum Algorithm/Data Structure Questions
    Replies: 1
    Last Post: 18th March 2010, 22:59

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts