user2268587
user2268587

Reputation: 179

ArrayList sorting longest sequence

I'm not asking anyone to solve this for me, I just need a little push because I have no earthly idea on where to begin with this. All I know is that I should implement collections in this and have a sort.

Write a method longestSortedSequence that returns the length of the longest sorted sequence within a list of integers. For example, if a variable called list stores the following sequence of values:

[1, 3, 5, 2, 9, 7, -3, 0, 42, 308, 17]

then the call: list.longestSortedSequence() would return the value 4 because it is the length of the longest sorted sequence within this list (the sequence -3, 0, 42, 308). If the list is empty, your method should return 0. Notice that for a non-empty list the method will always return a value of at least 1 because any individual element constitutes a sorted sequence.

Assume you are adding to the ArrayIntList class with following fields:

public class ArrayIntList 
{
    private int[] elementData;
    private int size;

    // your code goes here
}

Upvotes: 6

Views: 774

Answers (4)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

Pseudo code:

Variable X: first item of list  
Variable Y: length of sequence (initial: 1)
Variable Z: max length occurred (initial: 0)  
Loop over the list starting from 2nd index  
 if item is higher than X  
  set X to item
  add 1 to Y  
 else  
  if Y is higher than Z
   set Z to Y
  end if
  set X to item  
  set Y to 1  
 end if  
End-Loop 

This method will restart the counter every time the sequence 'restarts', aka: it's no longer sorted. While the list is sorted it just adds 1 for each element that is in sorted order.

When the sequence stops being ordered it checks if the current sequence is longer than the longest sequence length so far. If it is, you have your new longest sequence.

Upvotes: 2

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6183

Iterate the array, and increment the counter variable if the next element you process is larger then the last one.

If the next element is smaller, or the end of the array is reached, store the current counter value if its larger then the currently stored max value and reset the counter variable with 0.

Upvotes: 3

Crickcoder
Crickcoder

Reputation: 2155

Loop over your array and compare i element with i+1 element. Make a counter. While i is less than i+1 increment the counter, when i is greater than i+1 reset the counter.

Upvotes: 0

coderatchet
coderatchet

Reputation: 8420

Have you thought about a for loop and if else statements? i hope this doesn't give it away. think one element at a time.

Upvotes: 1

Related Questions