Results 1 to 3 of 3
  1. #1
    gnawk is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default how to delete an element from a sorted array

    Hi im trying to delete a value from a sorted array but it does not seem to work
    when i run the program and try to delete a value it only decrements the size of the array by one.
    So the last value gets deleted everytime

    Java Code:
    	public void delete(Comparable T) {
    		int f = find(T);
    		if (empty() == true) {
    			System.out.println("The array is empty and nothing to delete.");
    			return;
    		}
    		for (int i = f; i == top - 1; i++){
    			array[i + 1] = array[i];
    		}
    		top--;
    	}
    public int find(Comparable T) {
    		int start = 0;
    		int end = top;
    		int midPoint;
    		while (start <= end) {
    			midPoint = (start + end) / 2;
    			if (array[midPoint].compareTo(T) == 0) {
    				return midPoint;
    			} else if (array[midPoint].compareTo(T) < 0) {
    				start = midPoint + 1;
    			} else
    				end = midPoint - 1;
    		}
    		return -1;
    	}

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,526
    Blog Entries
    7
    Rep Power
    20

    Default Re: how to delete an element from a sorted array

    Quote Originally Posted by gnawk View Post
    Java Code:
    		for (int i = f; i == top - 1; i++){
    			array[i + 1] = array[i];
    		}
    		top--;
    	}
    I don't think this entire loop makes any sense ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    gnawk is offline Member
    Join Date
    Feb 2012
    Posts
    17
    Rep Power
    0

    Default Re: how to delete an element from a sorted array

    Fixed it.... It was
    For (i =f; i<= top; i++)
    Not i==top

Similar Threads

  1. Keeping objects sorted in an array.
    By artur in forum New To Java
    Replies: 6
    Last Post: 02-28-2012, 12:46 AM
  2. Checking to see if Array is sorted
    By pytho in forum New To Java
    Replies: 5
    Last Post: 07-06-2011, 01:39 AM
  3. Delete Middle element from arrray
    By tttestall in forum New To Java
    Replies: 3
    Last Post: 04-24-2011, 07:25 PM
  4. Replies: 8
    Last Post: 04-22-2008, 03:21 AM
  5. Replies: 0
    Last Post: 04-14-2008, 08:39 PM

Posting Permissions

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